Page 1 of 1

replace array elements with highlighted text in a text

Posted: Wed Dec 05, 2007 4:00 am
by amitsri
hi,
i am trying to replace elements of an array in a text with their bold equivalent.
For example
i have this array

Code: Select all

$arr=Array('name1','name2','name3','name4','name5','name6','name7','name8','name9');
i have a text

lorem ipsum name5 lorem ipsum name2 lorem ipsum dolor name9

i want name5, name2 and name9 to be highlighted with some background color.

problem is what this is going to be time consuming if the array contains around 6000 elements i have to loop through each element and highlight the text if match is found.

Thanks in advance

Posted: Wed Dec 05, 2007 4:11 am
by s.dot
It could be done with a simple preg_replace().

Code: Select all

$formatted = preg_replace('/(' . preg_quote(implode('|', $arrayOfWords)) . ')/ism', '<b>' . "\\1" . '</b>', $unformatted);
I was thinking it could be done with str_replace(), but I don't know how to get the second parameter to recognize the words in the first parameter's array.

Posted: Wed Dec 05, 2007 5:34 am
by amitsri
scottayy wrote:It could be done with a simple preg_replace().

Code: Select all

$formatted = preg_replace('/(' . preg_quote(implode('|', $arrayOfWords)) . ')/ism', '<b>' . "\\1" . '</b>', $unformatted);
I was thinking it could be done with str_replace(), but I don't know how to get the second parameter to recognize the words in the first parameter's array.

it gives this error:

Warning: preg_replace() [function.preg-replace]: Unknown modifier 'P' in /home/admin/domains/netglimse.com/public_html/celeb_names.php on line 10

Posted: Wed Dec 05, 2007 7:40 am
by s.dot
try changing the / at the beginning and end of the regex to #

Posted: Wed Dec 05, 2007 7:54 am
by superdezign
scottayy wrote:try changing the / at the beginning and end of the regex to #
Note that by doing so, you may want to include the delimiter in the preg_quote() call as well.

Also, echo the resulting regex so we can see what the error is referring to.

Posted: Wed Dec 05, 2007 10:50 am
by feyd
preg_quote() needs to be run before implode() unfortunately.