【问题标题】:PHP regex replace from string to stringPHP正则表达式从字符串替换为字符串
【发布时间】:2014-11-11 06:01:37
【问题描述】:

我想替换以一个字符串开头并以另一个字符串结尾的字符串的一部分,并且我希望这之间的部分也被替换。我认为使用正则表达式可以做到这一点,但我似乎找不到任何合适的例子来说明这一点。

例如:

I have "http://www.website.com" and I want to replace from "www" to "com" with "123xyz".
So"http://www.website.com/something" becomes "http://123xyz/something.

我假设我必须使用 preg_replace(),并且我认为正则表达式应该以“^www”开头并以“com$”结尾,但我似乎无法掌握足够的正则表达式语法来创建想要的效果。

请帮忙

【问题讨论】:

  • 请查看我对您的查询的回答。

标签: php regex string replace


【解决方案1】:

参考你的例子,你可以这样尝试

$string = 'http://www.website.com/something';
$pattern = '/www(.*)com/';

$replacement = '123xyz';
echo preg_replace($pattern, $replacement, $string);

【讨论】:

    【解决方案2】:
    $phrase       = "http://www.website.com";
    $phraseWords  = array("www", "com");
    $replaceTo    = array("123xyz", "something");
    
    $result = str_replace($phraseWords, $replaceTo, $phrase);
    echo $result;
    

    【讨论】:

      【解决方案3】:

      非常感谢@CodingAnt 和@PHPWeblineindia 的出色回答。使用@CodingAnt 的答案(以及我在网上进行的一些研究)我编写了这个函数:

      function replaceBetween(&$target, $from, $to, $with){
        if(strpos($target, $from)===false)return false;
        $regex = "'".$from."(.*?)".$to."'si";
        preg_match_all($regex, $target, $match);
        $match = $match[1];
        foreach($match as $m) $target = str_replace($from.$m.$to, $with, $target);
        return $target;
      }
      

      它似乎工作得很好。我希望有人觉得这很有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-04
        • 1970-01-01
        • 1970-01-01
        • 2018-07-13
        相关资源
        最近更新 更多