2017-05-10 298 views
-2

如何替换PHP只有第一个字和第二个字而不是替换第三个字?如何只替换PHP的第一个字和第二个字而不是替换第三个字?

$test = "hello i love animal love dog and and love tree"; 

我想更换最前一页和secode字loveunderscore,而不是取代第三字love这样。

hello i _ animal _ dog and and love tree 

然后,我用这个代码

$test = str_replace('love', '_', $test); 
echo $test; 

但结果将是

hello i _ animal _ dog and and _ tree 

如何我可以只更换第一和第二个字,而不是取代第三个单词吗?

+0

的可能的复制(HTTP [PHP STR \ _replace()有限制PARAM?]://计算器。 com/questions/8510223/php-str-replace-with-a-limit-param) – Rulisp

+0

@Rulisp对str_replace()没有限制参数,有一个计数参数,但允许你传入一个变量作为指针为了获得被替换的字符串的实例数量。它实际上并不允许您限制要替换的实例的数量。 – Dave

回答

0

我认为这是你正在寻找的结果是:

$subject = "hello i love animal love dog and and love tree"; 
$search = "love"; 
$replace = "_"; 

$pos = strrpos($subject, $search); 

$first_subject = str_replace($search, $replace, substr($subject, 0, $pos)); 
$subject = $first_subject . substr($subject, $pos, strlen($subject)); 

echo $subject; 

演示here

+1

哦最好的答案^ _ ^ –

0

这是一个免费的正则表达式路:

码(Demo):

$test = "hello i love animal love dog and and love tree"; 
$test=substr_replace($test,"_",strpos($test,"love"),4); 
$test=substr_replace($test,"_",strpos($test,"love"),4); 
echo $test; 

输出:

hello i _ animal _ dog and and love tree 

这种方法非常简单,因为它同样的方法两次 - 每次消除“一见钟情”。

+0

不工作,我想输出'你好我_动物_狗和爱树'我怎么办? –

+0

@mongkontiya对不起我的错误,我已经解决了我的方法。我认为这比我的第一种方法更简单。 – mickmackusa

相关问题