0

I'm reading in an HTML string from a text editor and need to manipulate some of the elements before saving it to the DB.

What I have is something like this:

<h3>Some Text<img src="somelink.jpg" /></h3>

or

<h3><img src="somelink.jpg" />Some Text</h3>

and I need to put it into the following format

<h3>Some Text</h3><div class="img_wrapper"><img src="somelink.jpg" /></div>

This is the solution that I came up with.

$html = '<html><body>' . $field["data"][0] . '</body></html>';

$dom = new DOMDocument();
$dom->loadHTML($html);

$domNodeList = $dom->getElementsByTagName("img");

// Remove Img tags from H3 and place it before the H# tag
foreach ($domNodeList as $domNode) {
    if ($domNode->parentNode->nodeName == "h3") {
        $parentNode = $domNode->parentNode;
        $parentParentNode = $parentNode->parentNode;

        $parentParentNode->insertBefore($domNode, $parentNode->nextSibling);
    }
}

echo $dom->saveHtml();
1

2 Answers 2

1

You may be looking for a preg_replace

// take a search pattern, wrap the image tag matching parts in a tag
// and put the start and ending parts before the wrapped image tag.
// note: this will not match tags that contain > characters within them,
//       and will only handle a single image tag
$output = preg_replace(
    '|(<h3>[^<]*)(<img [^>]+>)([^<]*</h3>)|',
    '$1$3<div class="img_wrapper">$2</div>',
    $input
);
Sign up to request clarification or add additional context in comments.

2 Comments

note2: this won't move the image out of the heading, better to use DOM here
Oops, missed that part of the question. Thank you.
1

I updated the question with the answer, but for good measure, here it is again in the answers section.

$html = '<html><body>' . $field["data"][0] . '</body></html>';

$dom = new DOMDocument();
$dom->loadHTML($html);

$domNodeList = $dom->getElementsByTagName("img");

// Remove Img tags from H3 and place it before the H# tag
foreach ($domNodeList as $domNode) {
    if ($domNode->parentNode->nodeName == "h3") {
        $parentNode = $domNode->parentNode;
        $parentParentNode = $parentNode->parentNode;

        $parentParentNode->insertBefore($domNode, $parentNode->nextSibling);
    }
}

echo $dom->saveHtml();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.