我有一个以下字符串:
$feed_status = Nice <img src='"http://52.1.47.143/file/pic/emoticon/default/smile.png'" alt='"Smile'" title='"Smile'" title='"v_middle'" /> to see <img src='"http://52.1.47.143/file/pic/emoticon/default/happy.png'" alt='"Smile'" title='"Smile'" title='"v_middle'" /> you all back again <img src='"http://52.1.47.143/file/pic/emoticon/default/tongue.png'" alt='"Smile'" title='"Smile'" title='"v_middle'" />;
我有另一个名为$emoticon_codes
的数组,其中包含三个元素,需要将它们放在上面的字符串中,以代替<img>
标签。
Array
(
[0] => 'ue056
[1] => 'ue057
[2] => 'ue105
)
字符串中的三个<img>
标记应按相同顺序替换为以上三个字符串。
我应该如何以最佳方式实现这一点?
请帮帮我。提前谢谢。
打印后我的最后一个字符串应该是这样的:
很高兴看到大家再次回来''ue057''ue105
我尝试了以下方法:
$doc = new DOMDocument();
$doc->loadHTML($feed_status);
$imageTags = $doc->getElementsByTagName('img');
if(count($imageTags)) {
$emoticon_codes = array();
foreach($imageTags as $tag) {
/*echo basename($tag->getAttribute('src'));
echo "<br>";*/
if (basename($tag->getAttribute('src')) == 'evilgrin.png') {
array_push($emoticon_codes, ''ue404');
}
if (basename($tag->getAttribute('src')) == 'grin.png') {
array_push($emoticon_codes, ''ue415');
}
if (basename($tag->getAttribute('src')) == 'happy.png') {
array_push($emoticon_codes, ''ue057');
}
if (basename($tag->getAttribute('src')) == 'smile.png') {
array_push($emoticon_codes, ''ue056');
}
if (basename($tag->getAttribute('src')) == 'surprised.png') {
array_push($emoticon_codes, ''ue107');
}
if (basename($tag->getAttribute('src')) == 'tongue.png') {
array_push($emoticon_codes, ''ue105');
}
if (basename($tag->getAttribute('src')) == 'unhappy.png') {
array_push($emoticon_codes, ''ue403');
}
if (basename($tag->getAttribute('src')) == 'waii.png') {
array_push($emoticon_codes, ''ue407');
}
if (basename($tag->getAttribute('src')) == 'wink.png') {
array_push($emoticon_codes, ''ue405');
}
}
}
未测试,但这将是"正确"的方法:
$arr = array('ue056, 'ue057, 'ue058);
$html = 'your html string here';
$i = 0;
$dom = new DOM();
$dom->loadHTML($html);
$images = $dom->getElementsByTagName('img');
foreach($images as $img) {
$img->parentNode->replaceChild($img, $dom->createTextNode($arr[$i]));
$i++;
if ($i > count($arr)) {
break;
}
}