开发者

Replace all words from array in php

How can I find & highlight all words from array in text?

example:

$words = array('Test', 'I', 'tHiS', 'diFFerent');

Expecting result is: Hi, i'm in this simple test I'd like to sho开发者_开发问答w you who we can replace different words.


$str = preg_replace("~(".implode("|" , array_map(function($a){
    return preg_quote($a,"~");
},$words)).")~i" , "<strong>$1</strong>" , $str);

you may try

$str = preg_replace("~(".implode("|" , array_map(function($a){
    return '\b'.preg_quote($a,"~").'\b';
},$words)).")~i" , "<strong>$1</strong>" , $str);

to specify that it should be full word


$words = array('Test', 'I', 'tHiS', 'diFFerent');
$str = "Hi, i'm in this simple test I'd like to show you who we can replace different words.";
$str = preg_replace("/(".implode("|" , $words).")/i" , "<b>$1</b>" , $str);
echo $str;

However, this will highlight all "I" in the string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜