使用PHP关闭或修复损坏的img标签 [英] Close or Fix a broken img tag using PHP

查看:66
本文介绍了使用PHP关闭或修复损坏的img标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用PHP修复损坏的" html字符串时遇到麻烦

I'm having troubles fixing a 'broken' html string, using PHP

我面临在html字符串上使用substr的常见问题,这会导致标记损坏.

I'm facing the common problem of using substr on an html string, which results in broken tags.

我已经设法修复了所有损坏的标签,除了图像标签,因为标签本身并不完整,甚至都不是开头标签,

I've managed to fix all the broken tags, except the image one, as the tag itself is not complete, it's not even an opening tag,

例如,假设您有一个字符串:

For example, Suppose you have a string:

<div><img alt="foo" title="bar" 

我真的很想添加一个>来关闭它,而我的其他脚本知道如何自动关闭div.

I'd really want to to add a > to close this, and my other scripts know how to close the div automatically.

有人对捕获损坏的<img>标签并自动修复它们有任何想法吗?

Does anyone have any ideas on how to catch broken <img> tags and automatically fix them?

我已经看到了许多解决方案,包括DOMdocument,tidy和HTMLpurifier,但它们似乎无法解决此特定问题.

I've seen many solutions including DOMdocument, tidy and HTMLpurifier, but they don't seem to fix this specific problem.

任何帮助将不胜感激.

推荐答案

是的,您可以使用DOMDocument修复标签. (基于示例):

Yes you can repair tags using DOMDocument. (Based on example):

$html = '<div><img alt="foo" title="bar"';
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();

$out = '';
foreach ($dom->getElementsByTagName('body')->item(0)->childNodes as $child) {
    $out .= $dom->saveXML($child);
}
echo htmlentities($out);


  • > 小提琴演示

    • Fiddle demo
    • 这篇关于使用PHP关闭或修复损坏的img标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆