简体   繁体   English

PHP正则表达式从字符串替换为字符串

[英]PHP regex replace from string to string

I want to replace a section of a string based that starts with one string and ends with another, and I want the section between also replaced. 我要替换基于字符串的部分,该部分以一个字符串开头,以另一个字符串结束,并且我也希望替换之间的部分。 I think this is possible using regex but I cant' seem to find any decent examples showing this. 我认为使用正则表达式是可能的,但是我似乎找不到任何合适的例子来说明这一点。

For Example: 例如:

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.

I am assuming I have to use preg_replace(), and I think the regex should start with "^www" and end with "com$", but I cant seem to get a grasp of the syntax of regex enough to create the desired effect. 我假设我必须使用preg_replace(),并且我认为正则表达式应以“ ^ www”开头并以“ com $”结尾,但是我似乎无法充分了解正则表达式的语法以产生所需的效果。

please help 请帮忙

With reference to your example , you can try like this 参考您的示例,您可以尝试这样

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

$replacement = '123xyz';
echo preg_replace($pattern, $replacement, $string);
$phrase       = "http://www.website.com";
$phraseWords  = array("www", "com");
$replaceTo    = array("123xyz", "something");

$result = str_replace($phraseWords, $replaceTo, $phrase);
echo $result;

Thanks so much to both @CodingAnt and @PHPWeblineindia for your great answers. 非常感谢@CodingAnt和@PHPWeblineindia的出色回答。 Using @CodingAnt's answer (and some more research I did online) I wrote this function: 使用@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;
}

It seems to work pretty well. 看来效果很好。 I hope someone finds this useful. 我希望有人觉得这有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM