【发布时间】:2021-12-27 00:44:05
【问题描述】:
我正在寻找一个简单的解决方案,该解决方案将用围绕每个字符串的 html 代码替换字符串数组,并且我还希望避免重复。例如:
数组是$things=array("apple","apple pie","baked apple");
要替换的是$toReplace="Henry ate an apple then a whole apple pie and a baked apple, too."
我希望它是Henry ate an <i>apple</i> then a whole <i>apple pie</i> and a <i>baked apple</i>, too.
我现在的代码是这样的:
foreach($things as $thing) $output=str_replace($thing,"<i>".$thing."</i>",$toReplace);
但是,我会得到不需要的结果,例如 Henry ate an <i>apple</i> then a whole <i><i>apple</i> pie</i> and a <i>baked <i>apple</i></i>, too. 或 Henry ate an <i>apple</i> then a whole <i>apple</i> pie and a baked <i>apple</i>, too.,具体取决于 $things 数组的顺序。
$things 数组中会有不同的字符串,并且可能有不同的顺序,所以有没有一种方法可以确保在所有处理完成后标签中不会嵌套任何标签,并且较长的字符串优先在较短的?
解决方案越简单越好。
【问题讨论】:
-
您需要更改顺序,以便首先替换更具体的顺序。像这样:$things = array("apple pie", "baked apple", "apple");
-
是的,但是有不需要的嵌套 元素。
-
@lukas.j 这无济于事。它将替换
apple pie,然后在替换中替换apple。 -
将单词列表转换为正则表达式,如
apple pie|backed apple|apple,然后使用preg_replace()。
标签: php str-replace