...

View Full Version : PHP Highlight



UrbanTwitch
09-01-2009, 03: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?

Fou-Lu
09-01-2009, 03: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?

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

Fou-Lu
09-01-2009, 04:16 AM
/(great|learn)/
Try that. Also, you can use an array and implode them on | to get a similar result.

UrbanTwitch
09-01-2009, 04: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

Fou-Lu
09-01-2009, 04: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).



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum