php - 如何仅替换 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
解决方案
您可能正在寻找这样的东西:
function replace($str,$from,$to){
$str = preg_replace('~('.preg_quote($from).')$~',$to,$str);
return $str;
}
请注意,文档说不要使用preg_quote
in preg_replace
,但老实说我不知道为什么。如果您知道,请发表评论。
推荐阅读
- huawei-mobile-services - 分析工具包 - 当来自连接输入流操作异常的响应内容时!40
- swiftui - SwiftUI - 删除 NavigationView?
- c++ - 澄清CMAKE库安装
- algorithm - 找到偶数位数的数字?
- python - 其他类方法的类装饰器
- apache-kafka - Kafka Stream - 自动提交关闭时如何处理错误
- iis - IIS ipSecurity 不阻止外部 IP
- angular - 在 rxjs/Observables 范围内,变量名后面的美元符号是什么意思?
- swift - SwiftUI:从 AppDelegate 中的函数更改 ContentView 中的变量
- typescript - 如何在 TypeScript 中强制使用扩展运算符创建的对象的类型安全