Search code examples
phpcase-insensitivestr-replace

PHP insensitive replace


I am trying to insensitive replace string, so I'm using str_ireplace() but it does something I dont want and I have no clue how to overcome this problem.

so this is my code:

$q = "pArty";
$str = "PARty all day long";
echo str_ireplace($q,'<b>' . $q . '</b>',$str);

The output will be like that: "<b>pArty</b> all day long". The output looks like that because I replace insenitive variable $q with its sensitive.

How can I overcome this so the output will be "<b>PARty</b> all day long"?


Solution

  • You could do this with preg_replace, e.g.:

    $q = preg_quote($q, '/'); // in case it has characters of significance to PCRE
    echo preg_replace('/' . $q . '/i', '<b>$0</b>', $str);