$string =‘你好,Hooman住在地球上,Hooman喜欢猫。’;
现在,我想将2 Hooman单词替换为Human,其结果应该如下:
你好。胡曼住在地球上。人类爱猫。--
我到目前为止所做的.
<?php
$string = 'Hellow there. Hooman lives on earth. Hooman loves cats.';
echo preg_replace('/Hooman/', 'Human', $string, 2);
?>但是它回来了:你好。地球上的人类生命。人类爱猫。--
发布于 2019-06-21 07:25:04
您可以使用preg_replace
function str_replace_n($search, $replace, $subject, $occurrence)
{
$search = preg_quote($search);
return preg_replace("/^((?:(?:.*?$search){".--$occurrence."}.*?))$search/", "$1$replace", $subject);
}
echo str_replace_n('Hooman','Human',$string, 2);发布于 2019-06-21 07:33:42
此代码假定字符串中至少有一个Hooman。
找到Hoomans的位置并在那里进行子字符串,然后在字符串的第二部分进行替换。
$find = "Hooman";
$str = 'Hellow there. Hooman lives on earth. Hooman loves cats.';
$pos = strpos($str, $find);
echo substr($str, 0, $pos+strlen($find)) . str_replace($find, "Human", substr($str, $pos+strlen($find)));https://stackoverflow.com/questions/56698557
复制相似问题