preg_replace wont stop escaping my double quotes!

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jbourne
Forum Newbie
Posts: 3
Joined: Sun Apr 10, 2011 2:49 pm

preg_replace wont stop escaping my double quotes!

Post 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.
fugix
Forum Contributor
Posts: 207
Joined: Fri Mar 18, 2011 8:01 pm

Re: preg_replace wont stop escaping my double quotes!

Post by fugix »

i prefer str_replace()..look into it if you're still having trouble
jbourne
Forum Newbie
Posts: 3
Joined: Sun Apr 10, 2011 2:49 pm

Re: preg_replace wont stop escaping my double quotes!

Post 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..
Post Reply