我正在尝试使用正则表达式在php中执行以下操作。
示例字符串:"懒狗吠叫。懒惰的疯狗。
我想将其更改为:
"the <tag>lazy</tag> dog barked. <tag>Lazy</tag> crazy dog."
所以我想围绕懒惰的每个实例,无论大小写
我知道您可以使用像"/''blazy''b/i"这样的正则表达式来选择懒惰的人。
对于我的生活,我不知道如何使用preg_replace来替换单词,而不管大小写如何,用标签包围的相同单词。
感谢协助。
您可以在
此实例中使用preg_replace_callback http://php.net/manual/en/function.preg-replace-callback.php。
$string = "the lazy dog barked. Lazy crazy dog.";
$result = preg_replace_callback('/lazy/i', function ($item) {
return '<tag>' . $item[0] . '</tag>';
}, $string);
echo $result;
具有分组功能的preg_replace
应该能够完成此操作:
$string = "the lazy dog barked. Lazy crazy dog.";
echo preg_replace('/'b(lazy)'b/i', '<tag>$1</tag>', $string);
输出:
the <tag>lazy</tag> dog barked. <tag>Lazy</tag> crazy dog.
如果要替换多个术语,请在每个术语之间使用 或 ( |
)。
例如:
echo preg_replace('/'b(lazy|tired)'b/i', '<tag>$1</tag>', $string);
这会将lazy
和tired
置于tag
元素中。
正则表达式101演示:https://regex101.com/r/hT6xR5/1
PHP 演示:https://eval.in/512715