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.

2
  • You could use PHP's DOM implementation, specifically the Document Fragment part. Parse it into DOM, manipulate it, then serialise it back into HTML. Commented Dec 14, 2015 at 11:11
  • So may you give me some demo?, i'm a new guy Commented Dec 14, 2015 at 11:20

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Please avoid link only answers. Answers that are "barely more than a link to an external site” may be deleted.
So may you give me some demo?, i'm a new guy
I've edited my answer, sorry guys. :)
No problem, thanks you so much neodem. It's work.:)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.