【问题标题】:How to replace only a specific word from the end of the string in PHP? [closed]如何仅替换 PHP 中字符串末尾的特定单词? [关闭]
【发布时间】: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

【问题讨论】:

  • 我不明白......它不会在操作后返回“这房子是我的”,你的意思是这是一个想要的结果? “它会回来的……”
  • 什么是replacelast 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


【解决方案1】:

根据您提到的条件,您可以执行以下操作。查找字数,然后检查字符串中是否有 home 可用,然后查找 house 的索引。那么您可以检查该索引是否与单词数组(count($wordArray)) - 1)的最后一个索引匹配

$string1 = 'this is my house';
    $string2 = 'this house is mine';
    $wordArray = explode(' ', $string1); // make the array with words
    //check the conditions you want 
    if (in_array('house', $wordArray) && (array_search('house', $wordArray) == (count($wordArray)) - 1)) {
        $string1 = str_replace('house', 'dog', $string1);
    }
    echo $string1;

【讨论】:

    【解决方案2】:

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

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

    请注意,文档中说不要在 preg_replace 中使用 preg_quote,但老实说,我不知道为什么。知道的请留言。

    【讨论】:

    • 恕我直言,不应该回答没有任何实际尝试解决问题的问题。这只是将这个网站简化为免费的编码服务。
    • 是的,但有时你只是不知道从哪里开始(也许不是这样)
    • 关于preg_quote 的注释用于替换,而不是模式。
    • 在我的答案甚至没有被选为正确答案之后,即使它是第一个,我也同意第一条评论并将其作为绝对规则
    猜你喜欢
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 2012-10-29
    • 2011-04-10
    • 1970-01-01
    • 2012-09-14
    相关资源
    最近更新 更多