[nycphp-talk] PHP STRING QUESTION
Dan Cech
dcech at phpwerx.net
Tue Oct 19 15:59:02 EDT 2004
Ophir Prusak wrote:
> Woops - I read your code to fast :)
> I didn't see you were doing this for multiple key words.
>
> In any case though it would be good to use the \b word boundry
> modifier so you won't be highlighting substring word matches.
The word boundary modifier is a good idea if that's what you want, but
be careful about constructing preg strings without using preg_quote, you
can get into real trouble if the user enters something odd.
The syntax should be:
function highlight($keyword, $text) {
return preg_replace('/\b'. preg_quote($keyword,'/')
.'\b/i','<b>$0</b>',$text);
}
Note that the character used to delimit the preg expression (in this
case /) is passed as the second parameter to preg_quote.
I'm not sure exactly why but the PHP manual indicates that $0 is the
preferred form for backreferences in the replacement string since 4.04.
From http://php.net/preg_replace
> Replacement may contain references of the form \\n or (since PHP 4.0.4) $n, with the latter form being the preferred one.
Dan
> On Tue, 19 Oct 2004 15:41:20 -0400, Ophir Prusak <prusak at gmail.com> wrote:
>
>>Just curious, why are you exploding the string into an array?
>>You can just do:
>>
>> function highlight($keyword, $text) {
>> $text = preg_replace('/\b' . $keyword .
>>'\b/i','<b>\\0</b>',$text);
>> return $text;
>>
>>
>> }
>>
>>On Tue, 19 Oct 2004 14:59:52 -0400, Mark Armendariz <nyphp at enobrev.com> wrote:
>>
>>>>I am able to search the word using the stristr()
>>>>function in php. This function is non-case sensitive.
>>>>However, I want to display the searched word in the line as highlighted in
>>>
>>>a
>>>
>>>>different color than the line.
>>>
>>>I wasn't sure if you wanted to return a line from the text (which Dan seems
>>>to have taken care of pretty well) or if you just wanted to replace words
>>>with formatted versions of themselves. Here's a really basic function I use
>>>to do the latter with multiple keywords (sep. by spaces):
>>>
>>><?php
>>> function highlight($keywords, $text) {
>>> $keywords = trim($keywords);
>>>
>>> if (strlen($keywords)) {
>>> $keywords = explode(' ', $keywords);
>>>
>>> if (count($keywords)) {
>>> foreach($keywords as $keyword) {
>>> // you could, of course use whatever html formatting
>>>you want here
>>> $text = preg_replace('/(' . $keyword . ')/i',
>>>'<b>\\1</b>', $text);
>>> }
>>> }
>>> }
>>>
>>> return $text;
>>> }
>>>?>
>>>
>>>Good Luck!
>>>
>>>Mark
More information about the talk
mailing list