开发者

Replace all words from array in php

开发者 https://www.devze.com 2023-04-12 03:43 出处:网络
How can I find & highlight all words from array in text? example: $words = array(\'Test\', \'I\', \'tHiS\', \'diFFerent\');

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

精彩评论

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

关注公众号