0

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.

please help

1
  • Please check my answer for your query. Commented Nov 11, 2014 at 6:17

3 Answers 3

2

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);
0
$phrase       = "http://www.website.com";
$phraseWords  = array("www", "com");
$replaceTo    = array("123xyz", "something");

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

Thanks so much to both @CodingAnt and @PHPWeblineindia for your great answers. Using @CodingAnt's answer (and some more research I did online) I wrote this function:

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.