gpt4 book ai didi

php - 我想用 php 正则表达式用 She 替换 He

转载 作者:行者123 更新时间:2023-12-02 19:25:36 26 4
gpt4 key购买 nike

我使用下面的代码将他替换为她,将他替换为她。

 $string = 'The quick he fox jumps over the lazy dog.';
$patterns = array();
$patterns[0] = '/he/';
//$patterns[1] = '/brown/';
//$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'she';
//$replacements[1] = 'black';
//$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);

但是执行后它返回以下字符串

Tshe quick she fox jumps over tshe lazy dog.

所以问题是它也在将“the”转换为“tshe”我只想替换单独的单词(像He)而不是单词的一部分(不像)。

最佳答案

试试这个:这只会替换整个单词

如果 $string 包含 UTF-8 文本,则必须添加 Unicode 修饰符“u”,以便非拉丁字符不会被误解为单词边界:

$string = 'The quick he fox jumps over the lazy dog.';

$replace = preg_replace('/\bhe\b/u', 'she', $string);

echo $replace;

关于php - 我想用 php 正则表达式用 She 替换 He,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46768790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com