John
John

Reputation: 171

Replace the images with their alt attribute PHP

This is the HTML code:

<div class="comment-content" contenteditable="true">
     Hello all<br/>
    <img alt="😂" class="emojioneemoji" src="https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.7/assets/png/1f602.png">
    <img alt="😂" class="emojioneemoji" src="https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.7/assets/png/1f602.png">
    <img alt="😂" class="emojioneemoji" src="https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.7/assets/png/1f602.png">
</div>

I want a PHP code to search content if it images and replaces the images with their alt attribute.

I want the output to be:

<div class="comment-content" contenteditable="true">
     Hello all<br/>
    😂
    😂
    😂
</div>

I try to make this by using Regex and this is my code but it's not working:

preg_replace('/<img.*?alt="(.*?)"[^\>]+>/g', '$1', $comment_content)

Any guide really appreciate.

Thank you.

Upvotes: 0

Views: 57

Answers (1)

Ermac
Ermac

Reputation: 1250

<?php
$html = '<div class="comment-content" contenteditable="true">
     Hello all<br/>
    <img alt="😂" class="emojioneemoji" src="https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.7/assets/png/1f602.png">
    <img alt="😂" class="emojioneemoji" src="https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.7/assets/png/1f602.png">
    <img alt="😂" class="emojioneemoji" src="https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.7/assets/png/1f602.png">
</div>';
$dom = new DOMDocument();
$dom->loadHTML('<html><head><meta charset="utf-8"></head><body>' . $html . '</body></html>');
while ($dom->getElementsByTagName('img')->length) {
    $oldnode = $dom->getElementsByTagName('img')[0];
    $newnode = $dom->createTextNode($oldnode->getAttribute('alt'));
    $oldnode->parentNode->replaceChild($newnode, $oldnode);
}

header('Content-Type: text/html; charset= UTF-8');
echo $dom->saveHTML($dom->getElementsByTagName('div')[0]);

Upvotes: 1

Related Questions