2

I have a list of items. I want to use them in search terms. Say the list is:

  • Hello, World!
  • The World is not Enough
  • Around the world in 80 days.
  • WAR of the WORLDS

Now, if I am searching for the keyword world (notice all are in small letters), I am giving this function.

preg_replace(/world/, '<span class="label label-search-results">$0</span>', $item);

Where the $item is each line, the output is:

Warning: preg_replace() [function.preg-replace]: Delimiter must not be alphanumeric or backslash in /myfile.php on line XX.

If I use str_ireplace(), I don't know the original case of the found text. It would be something like:

str_ireplace("world", '<span class="label label-search-results">world</span>', $item);

And that results in all the world, World and WORLD being in lower case. Any ideas on how to preserve the case after replace?

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252

2 Answers2

1

That's the perfect use case for preg_replace_callback(), just use it like this:

echo preg_replace_callback("/" . preg_quote($_GET["q"], "/")  . "/i", function($m){
    return "<span class='label label-search-results'>" . $m[0] . "</span>";
}, $item);
Rizier123
  • 58,877
  • 16
  • 101
  • 156
0
preg_replace('/(world)/i', '<span class="label label-search-results">$1</span>', $item);

Try with the flag i for case-insensitivity.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
jskidie
  • 154
  • 6