Page 1 of 1

preg_replace wont stop escaping my double quotes!

Posted: Sun Apr 10, 2011 3:00 pm
by jbourne
I don't get this, and it's driving me crazy.

I'm adding HTML to a database table and loading it dynamically and displaying it on my page. This part works.

Now I've changed the form where I insert the HTML. I want to scan through to HTML content that's being added and automatically add target="_blank" to the <a> tags if they aren't there already, some HTML may have multiple <A> tags some may have none. Here's what I got:

Code: Select all

  $matches;
  $skipper = "";
  if (preg_match_all("/<a\s*[^>]*>/si",$html,&$matches)) { //Does the HTML contain a link..
    for($i=0;$i<count($matches[0]);$i++) { //for each link
      if(!(preg_match("/<a[^>]*\starget=[^>]*>/",$matches[0][$i]))) { //Link doesn't load in an empty page..fix it.
        $html = preg_replace("/(".$skipper.".*?<a\s)/sim","'$1 target=\"_blank\" '",$html);
      }
      $skipper .= ".*?<a[^>]*>";
    }
  }
The code works as I expect it too except that in the resultant code the portions replaced with the $1 bit have escaped slashs and double-quotes.

Thanks for any advice or help!

Jason.

Re: preg_replace wont stop escaping my double quotes!

Posted: Mon Apr 11, 2011 6:46 pm
by fugix
i prefer str_replace()..look into it if you're still having trouble

Re: preg_replace wont stop escaping my double quotes!

Posted: Mon Apr 11, 2011 11:15 pm
by jbourne
Thanks for the recommend, I checked out str_replacce() it looks pretty straight forward. I think I'm going to use an HTML parser to parse the the HTML properly though and add the tag, I've decided it's the cleaner approach..