首页 > 解决方案 > 如何仅替换 PHP 中字符串末尾的特定单词?

问题描述

我有两个这样的字符串变量

$string1 = 'this is my house';
$string2 = 'this house is mine';

仅当“house”是字符串的最后一个单词时,我才需要一种将“house”替换为“dog”的方法。

例如,这段代码

function replace($input_string, $search_string, $replace_string){
   //do the magic here!
}
$string1 = replace($string1, 'house','dog');
$string2 = replace($string2, 'house','dog');

echo $string1;
echo $string2;

期望的回报将是...

this is my dog
this house is mine

标签: phpstringreplacestr-replace

解决方案


您可能正在寻找这样的东西:

function replace($str,$from,$to){
    $str = preg_replace('~('.preg_quote($from).')$~',$to,$str);
    return $str;
}

请注意,文档说不要使用preg_quotein preg_replace,但老实说我不知道​​为什么。如果您知道,请发表评论。


推荐阅读