View Full Version : PHP Highlight

09-01-2009, 02:48 AM
OK so I got this code and it only works when I put ONE word with NO space in it:

$text = "CodingForums are a great place to learn how to code. Also a good place to give help. CodingForums are blank!";
$text = preg_replace("/great/i", "<span style=\"background:yellow\">\\0</span>", $text);
echo $text;

OK, if I put great learn instead of great... then it won't highlight. However, if I just put great. It will highlight great. Is there a way to make it highlight words spaced apart?

09-01-2009, 02:56 AM
You can use different words if you use a | to separate them.
Also, do you mean to highlight starting at great and ending with learn inclusive, or just the two words?

09-01-2009, 03:07 AM
just two words.

09-01-2009, 03:16 AM
Try that. Also, you can use an array and implode them on | to get a similar result.

09-01-2009, 03:23 AM
But the user would have to type in the search box "great|learn" to search for multiple words... unless I use explode for the space and |.
But after that... I'm lost. :\ I forgot how to count how many words were exploded. o_O

09-01-2009, 03:32 AM
You can just replace whatever you want.
If the user is expected to enter a space separated list, replace each space with a |, trimming any whitespace as necessary.
Use count() or sizeof() to get the number of items from an explode (since its just an array).