简体   繁体   中英

How to highlight multiple keywords in a mouthful in PHP?

Suppose there are 3 keywords,

I don't want to do this kind of replace 3 times:

a => <b>a</b>

str_replace ( 'a', '<b>a</b>', $str)

Is it possible to do it by one run?

You can use the strtr (or mb_strtr) function in PHP

$trans = array("hello" => "hi", "said" => "screamed");
echo strtr("hi all, I said hello", $trans);  // prints out "hi all, I screamed hi"

Use preg_replace() with a backreference:

$text = "foo bar baz";
echo preg_replace('/(a)/', '<b>$1</b>', $text);
preg_replace('/(a|e|i|o|u)/', '<b>$1</b>', $string);

您是否考虑过研究<b><strong>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM