Php 替换字符串中第二个出现的单词并返回整个字符串

Php 替换字符串中第二个出现的单词并返回整个字符串,php,Php,$string='Hellow在那里。胡曼生活在地球上。胡曼喜欢猫 现在,我想将第二个Hooman单词替换为Human,结果如下: 他在那里。胡曼生活在地球上。人类喜欢猫。 这是我到目前为止所做的…: <?php $string = 'Hellow there. Hooman lives on earth. Hooman loves cats.'; echo preg_replace('/Hooman/', 'Human', $string, 2); ?> 但是它返回:他

$string='Hellow在那里。胡曼生活在地球上。胡曼喜欢猫

现在,我想将第二个Hooman单词替换为Human,结果如下:

他在那里。胡曼生活在地球上。人类喜欢猫。

这是我到目前为止所做的…:

<?php

$string = 'Hellow there. Hooman lives on earth. Hooman loves cats.';

echo preg_replace('/Hooman/', 'Human', $string, 2);

?>


但是它返回:他在那里。人类生活在地球上。人类喜欢猫。

你可以用preg\u替换

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);

您可以使用preg_替换

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);

此代码假定字符串中至少有一个Hooman

$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)));
找到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)));

此代码假定字符串中至少有一个Hooman

$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)));
找到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)));

Hoomans
Hoomans
?我没有尝试我写的东西,它是否有效?您验证了anwser,然后取消了它的验证。
Hoomans
Hoomans
?我没有尝试我写的东西,它是否有效?你验证了anwser,然后又取消了它的验证。但是它在第二次发生后也替换了所有的Hooman。胡曼生活在地球上。胡曼喜欢猫。胡曼胡曼胡曼在那里变成了赫洛。胡曼生活在地球上。人类喜欢猫。人类,但在第二次发生后,它也取代了所有的胡曼人。胡曼生活在地球上。胡曼喜欢猫。胡曼胡曼胡曼在那里变成了赫洛。胡曼生活在地球上。人类喜欢猫。你的字符串有多长?如果我在$string中多行写Hooman-Hooman-Hooman,它根本不起作用。但是如果我把Hooman-Hooman-Hooman写在一行中,效果很好;现在它可以工作了。谢谢你的时间:)你的字符串有多长?如果我在$string中多行写Hooman-Hooman-Hooman-Hooman,它根本不起作用。但是如果我把Hooman-Hooman-Hooman写在一行中,效果很好;现在它可以工作了。谢谢您的时间:)