Skip to content
Advertisement

Check if str_replace Should Execute First to Avoid Duplicate Strings

Each time we save our ACF form, this snippet adds additional tags around the registered trademark symbol. Our goal is for it to do it just once, so we need to check for the tags first but don’t know how, as we’re quite new to PHP.

function superscript_R( $value, $post_id, $field ) {
if( is_string($value) ) {
    $value = str_replace(['®', '&reg;'],'<sup>®</sup>',  $value );
}
return $value;
}

// Apply to all fields
add_filter('acf/update_value', 'superscript_R', 10, 3);

Advertisement

Answer

You should check first if string contains and if it does just don’t replace.

function superscript_R( $value, $post_id, $field ) {
   if( is_string($value) && strpos($value, '<sup>') === false ) {
       $value = str_replace(['®', '&reg;'],'<sup>®</sup>',  $value );
   }
   return $value;
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement