用alt属性PHP替换图像

时间:2018-04-07 22:24:14

标签: 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>

我想要一个PHP代码来搜索内容,如果它成像并用alt属性替换图像。

我希望输出为:

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

我尝试使用Regex来实现这一点,这是我的代码,但它不起作用:

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

任何导游都非常感激。

谢谢。

1 个答案:

答案 0 :(得分:1)

<?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]);