PHP - 在处理冲突的子字符串时替换字符串数组的最佳方法?

PHP - Best way to replace array of strings while dealing with conflicting sub-strings?

我正在寻找一个简单的解决方案,将字符串数组替换为每个字符串周围的 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 = [ 'apple pie', 'baked apple', 'apple' ];
$toReplace = 'Henry ate an apple then a whole apple pie and a baked apple, too.';

echo preg_replace('/' . implode('|', $things) . '/i', '<i>[=10=]</i>', $toReplace);

感谢@Barmar。

请注意,它不适用于这样的商品订单 $things=array("apple","apple pie","baked apple");.