带有PHP preg_replace()的正则表达式需要在字符串中找到最近的名称
我需要在字符串中找到最接近的名称,我该怎么做 我得到的最接近的是合适的,它发现离字符串最远的是:带有PHP preg_replace()的正则表达式需要在字符串中找到最近的名称,php,regex,preg-replace,Php,Regex,Preg Replace,我需要在字符串中找到最接近的名称,我该怎么做 我得到的最接近的是合适的,它发现离字符串最远的是: $string = "joe,bob,luis,sancho,bob,marco,lura,hannah,bob,marco,luis"; $new_string = preg_replace('/(bob(?!.*bob))/', 'found it!', $string); echo $new_string; <!-- outputs: joe,bob,luis,sancho,bob,
$string = "joe,bob,luis,sancho,bob,marco,lura,hannah,bob,marco,luis";
$new_string = preg_replace('/(bob(?!.*bob))/', 'found it!', $string);
echo $new_string;
<!-- outputs: joe,bob,luis,sancho,bob,marco,lura,hannah,found it!,marco,luis -->
$string=“乔、鲍勃、路易斯、桑乔、鲍勃、马可、卢拉、汉娜、鲍勃、马可、路易斯”;
$new_string=preg_replace('/(bob(?!bob))/','found it!',$string);
echo$new_字符串;
我该怎么做呢?并有如下输出:
<!-- outputs: joe,found it!,luis,sancho,bob,marco,lura,hannah,bob,marco,luis -->
您使用的正则表达式
(bob(?。*bob))
匹配一行中最后出现的bob
(不是一个完整的单词),因为
匹配除换行符以外的任何字符,并且负向前看确保bob
之后没有bob
。请参阅(如果我们使用preg\u替换默认选项)
你可以用
$re = '/\bbob\b/';
$str = "joe,bob,luis,sancho,bob,marco,lura,hannah,bob,marco,luis";
$result = preg_replace($re, 'found it!', $str, 1);
看
regex\bbob\b
将匹配整个单词,并且使用limit
参数将仅匹配单词“bob”的第一次出现
见:
限制
每个主题字符串中每个模式的最大可能替换。默认值为-1
(无限制)
你可以试着做一个消极的回顾,就像这样
$string = "joe,bob,luis,sancho,bob,marco,lura,hannah,bob,marco,luis";
$new_string = preg_replace('/((?<!bob)bob)/', 'found it!', $string, 1);
echo $new_string;
<!-- outputs: joe,found it!,luis,sancho,bob,marco,lura,hannah,bob,marco,luisoff -->
$string=“乔、鲍勃、路易斯、桑乔、鲍勃、马可、卢拉、汉娜、鲍勃、马可、路易斯”;
$new_string=preg_replace('/(?尝试使用preg_replace的第四个参数(limit
)等于1Lookarounds是此任务不必要的开销。Wiktor的答案是最佳选择。