0

I am trying to create a filter for the_content() where I would be able to aply a str_replace() on specific caracters array().

At the moment, I have it working for only one caracter. I would like to be

function str_replace_special_caracter($content) {

    // My array of special caracters to get <sup>
    $specialCaracters = array('®', '™');

        // Special code to filter in array?

    // Return
    return str_replace('®', '<sup>®</sup>', $content);

}

add_filter( 'the_content', 'str_replace_special_caracter', 99 );

This simple solution is working. But as I may have new special caracter to place a <sup></sup> an array will be better.

Possible solution?

I saw people using strstr PHP Function and when I tried it, it did not quite worked. Maybe I am doing something wrong?

function str_replace_special_caracter($content) {

    // My array of special caracters to get <sup>
    $specialCaracters = array('®' => '<sup>®</sup>', '™' => '<sup>™</sup>');

        // Special code to filter in array?

    // Return
    return strstr($content, $specialCaracters);

}

add_filter( 'the_content', 'str_replace_special_caracter', 99 );

Resulting in an error : Warning: strstr(): needle is not a string or an integer in /home/.../functions.php on line 186

Everything I found on Stackexchange are "double-array" (https://stackoverflow.com/questions/2399286/str-replace-with-associative-array)

I'll keep investing, but if some one has a clue how I could do it, it would be nice.

  • look what is in $content, it can be NULL. – mmm Nov 29 '17 at 17:30
0

You could obtain what you need like this:

function str_replace_special_caracter($content) {

    // My array of special caracters to get <sup>
    $specialCaracters = array('®', '™');

    foreach( $specialCaracters as $character ){

        $content = preg_replace( '@(' . preg_quote( $character, '@' ) . ')@i', "<sup>\\1</sup>", $content );

    }

    // Return
    return $content;

}

add_filter( 'the_content', 'str_replace_special_caracter', 99 );
  • Looks like it is working. I'm not a "super-user" of preg_replace. I will have to read some documentation but your anwser fixed my problem. – Patrice Poliquin Nov 29 '17 at 18:14
  • I have updated my answer to remove the '\b' from the preg_replace as with it only characters that where at the beginning of a word would have been found. But that is not what you need. – freejack Nov 29 '17 at 18:57
  • Alright ! It is good to know. – Patrice Poliquin Nov 29 '17 at 18:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.