Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
    
Please check my answer for your query. –  PHP Weblineindia Nov 11 at 6:17

3 Answers 3

up vote 2 down vote accepted

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

$result = str_replace($phraseWords, $replaceTo, $phrase);
echo $result;
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.