首页 > 解决方案 > 在特定句子之间插入标签,保持原始大小写

问题描述

我需要在字符串中的某个文本之间插入一个 span 标签,但它应该不区分大小写并保留原始大小写。

$string ="This is what this is";

echo str_replace("this is","[span]this is[/span]",$string);

回报:

这就是 [span]这是[/span]

预期的:

[/span]这是[/span] 这是什么 [span]这是[/span]

我知道这str_replace不是一个好的选择,而且 ir 可能由 Regex 处理,但我不知道我应该朝哪个方向发展。在此先感谢您的帮助!

标签: phpregexpreg-replace

解决方案


使用preg_replace

$string ="This is what this is";

echo preg_replace("/this is/i","[span]$0[/span]",$string);

解释:

/           : regex delimiter
   this is  : literally
/i          : regex delimiter, case insensitive

替代品:

$0    : contains the whole match, ie "this is"

推荐阅读