Search code examples
phppreg-replacepreg-match

PHP - preg_replace multiple patterns, while keeping what's inbetween two other patterns


I've recently started using regex functions to simplify what I previously had. I'm attempting to turn this,

Some text
'[img="http://www.example.com/null.jpg"]'
Some more text

into this:

Some text
<img src="http://www.example.com/null.jpg">
Some more text

Is this possible in php using regex functions (such as 'preg_replace' and 'preg_match')?

***EDIT[

Here is my current clunky function

function filterimgorig($string)
{
  if(substr_count($string, '[img="')==substr_count($string, '"]') and         substr_count($string, '[img="')+substr_count($string, '"]')!=0)
  {
    $start =  strpos($string, '[img="')."<br/>";
    $end = strpos($string, '"]');
    $img = substr($string, $start+6, ($end - $start)-6);
    if (filter_var($img, FILTER_VALIDATE_URL) === false) {
      return htmlspecialchars(str_replace('&#39;',"'",$string));
    }
    else
    {
    return substr($string, 0, $start)."\r\n<img src='".$img."'>\r\n".substr($string, $end+2,strlen($string));
    }
  }
  else
  {
    return htmlspecialchars(str_replace('&#39;',"'",$string));
  }
}

Solution

  • You could do:

    $string = preg_replace("/'\[img=([^]]+)\]/", "<img src=$1>", $string);