【发布时间】:2021-02-19 22:21:51
【问题描述】:
我有两个这样的字符串变量
$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
【问题讨论】:
-
我不明白......它不会在操作后返回“这房子是我的”,你的意思是这是一个想要的结果? “它会回来的……”
-
什么是
replace?last word of the string,最后一次出现在字符串或单词中是什么意思?展示一些尝试和其他示例会有所帮助。例如this is my house....应该替换house吗? -
是的,你的意思是
str_replace?真的很难理解你的问题......如果它是狗的房子,你只想替换句子的最后一个词? -
你已经用 PHP 5.3 标记了这个问题。您知道 5.3 已超过 6 年没有得到支持(没有安全更新或任何东西)吗?如果您实际运行的是 5.3,那么您已经暴露在外,应该尽快升级。
-
do the magic here没有为问题添加任何内容preg_replace和$可能是您的起点。问题是目前含糊不清。 regular-expressions.info/anchors.html
标签: php string replace str-replace