如何只替换第一个和第二个单词而不替换第三个单词?
我有
$test = "hello i love animal love dog and and love tree";
我想将fisrt和secode字love
替换为underscore
,而不是像这样替换第三个字love
。
hello i _ animal _ dog and and love tree
然后我使用此代码
$test = str_replace('love', '_', $test);
echo $test;
但结果将是
hello i _ animal _ dog and and _ tree
如何才能更换第一个和第二个单词而不是替换第三个单词?
答案 0 :(得分: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
这种方法很简单,因为它会使用相同的方法两次 - 每次删除"一见钟情"。
答案 1 :(得分: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