tags:

views:

58

answers:

3

I has a string

 $text =<<<HTML
<div align="center"><center><img src='http://ecx.images-amazon.com/images/I/41KZa6thzcL._SS500_.jpg' alt="The Birthday of the World: And Other Stories"/></center><br/>
 thanks all "coder". </div>

   HTML;

I want replace all " from tag with \" or ' with \' and don't replace if " or ' not in tag

and result is

  $text =<<<HTML
    <div align=\"center\"><center><img src=\'http://ecx.images-amazon.com/images/I/41KZa6thzcL._SS500_.jpg\' alt=\"The Birthday of the World: And Other Stories\"/></center><br/>
     thanks all "coder".
    </div>
       HTML;

Please help me . Great Thanks

A: 

Get yourself a copy of RegExBuddy and I'd say you'd bang out a regular expression to do it reasonably quickly.

Toby Allen
"This answer available for the low, low price of $40."
Mike Daniels
Worth every cent.
Toby Allen
+2  A: 

Use a DOM parser such as PHP Simple HTML DOM Parser to traverse the HTML (yes it will work on HTML fragments such as the one in your example).

As you traverse, store the innerText in an array and replace that inner text with a place holder such as <![CDATA[INNER_TEXT_PLACE_HOLDER_0]]> (or whatever you choose, so long as it's something that won't be anywhere else in the DOM and has an integer that will match up with the array key in your innerTexts array).

Dump the DOM back to a string then do a global replace of the quotes.

Now loop through your innerTexts array, e.g.,

foreach ($innerTexts as $index => $innerText)

replacing <![CDATA[INNER_TEXT_PLACE_HOLDER_$index]]> with $innerText

webbiedave
Suggested third party alternatives to [SimpleHtmlDom](http://simplehtmldom.sourceforge.net/) that actually use [DOM](http://php.net/manual/en/book.dom.php) instead of String Parsing: [phpQuery](http://code.google.com/p/phpquery/), [Zend_Dom](http://framework.zend.com/manual/en/zend.dom.html), [QueryPath](http://querypath.org/) and [FluentDom](http://www.fluentdom.org).
Gordon
Thanks for the excellent list, Gordon.
webbiedave
A: 

This might not be quick, but it works:

$dom = new DOMDocument;
$dom->loadHTML($text);
$xPath = new DOMXPath($dom);

$str = array();
foreach($xPath->query('//text()') as $node) {
    $str['find'][] = addslashes($node->wholeText);
    $str['replace'][] = $node->wholeText;
}
$text = str_replace($str['find'], $str['replace'], addslashes($text));

echo $text;

gives (reformatted for readability):

<div align=\"center\">
  <center>
     <img src=\'http://ecx.images-amazon.com/images/I/41KZa6thzcL._SS500_.jpg\' 
          alt=\"The Birthday of the World: And Other Stories\"/>
  </center>
  <br/>thanks all "coder".
</div>
Gordon