Reply to Re: [PHP] str_replace on words?

Your name:

Reply:


Posted by Merlin on 05/12/05 09:20

Duncan Hill wrote:
> On Wednesday 11 May 2005 17:13, Merlin wrote:
>
>>Hi there,
>>
>>I am trying to strip some words from a sentence. I tried it with
>>str_replace like described here:
>>http://www.totallyphp.co.uk/code/find_and_replace_words_in_a_text_string_us
>>ing_str_replace.htm
>>
>>Unfortunatelly it does not work the way I want, because if I want to
>>replace the word "in" all passages containing the characters "in" are
>>replaced. For example Singapore.
>
>
> You need to tokenize your input and do exact matching. Alternately,
> preg_match / preg_replace may work with \b to specify word boundries.

Hi Duncan,

that in fact was the key and only way to get a proper result.
I found this script on the preg_replace page of php.net:
// Function highlights $words in $str
function highlight_words($str, $words) {
if(is_array($words)) {
foreach($words as $k => $word) {
$pattern[$k] = "/\b($word)\b/is";
$replace[$k] = '<b>\\1</b>';
}
}
else {
$pattern = "/\b($words)\b/is";
$replace = '<b>\\1</b>';
}
return preg_replace($pattern,$replace,$str);
}

Which works excellent!

Thanx, Merlin

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация