0

I have a string like this:

<p>title="abc" </p> <p title="a"><a title="b"></a></p><pre title="c"></pre>

I want to replace string title is class inside html tag and keep string 'title' outside html tag. Please tell me if you have any ideas. Thanks.

Mayank Vadiya
  • 1,437
  • 2
  • 19
  • 32

1 Answers1

1

If you want to do this with PHP, you should use DOMDocument. Maybe this SO post can help you.

edit : sorry for the linked-only answer. Here is a example of code :

$html = '<p>title="abc" </p><p title="a"><a title="b"></a></p><pre title="c"></pre>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $dom->getElementsByTagName('*');

foreach ($nodes as $node) {
    if ($node->getAttribute('title')) {
        $node->setAttribute('class', $node->getAttribute('title'));
        $node->removeAttribute('title');
    }
}
$html = $dom->saveHTML();
echo $html;

This code will give you :

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>title="abc" </p><p class="a"><a class="b"></a></p><pre class="c"></pre></body></html>

You can then remove header + extra tags (html/body) if you don't need it. Online example here

Community
  • 1
  • 1
neodern
  • 28
  • 5