How to replace text in html tag?

446 views Asked by At

I have 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 to replace all " from tag with \" or ' with \' and don't replace if " or ' not in tag

so 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

3

There are 3 answers

1
Toby Allen On

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

1
webbiedave On

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

0
Gordon On

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>