我有这样的字符串:
<h2 Article name</h2>This is an idea.<ul style="color:green;"><li>option 1</li><li>option 2</li><li>option 1<li></ul>
正如您所看到的,它是无效的,symfony 或 PHP 如何检测到它并返回错误所在?
我找到了以下代码:
private function validateHTML($string)
{
preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?>#iU', $string, $result);
$openedTags = $result[1];
preg_match_all('#</([a-z]+)>#iU', $string, $result);
$closedTags = $result[1];
$len_opened = count($openedTags);
return (count($closedTags) == $len_opened) ? $string : false;
}
但它有时效果很好,但不适用于我在顶部注意到的示例。
我使用的是 symfony 4.2
最佳答案
我认为最好的方法是渲染它,然后检查它的错误
测试这段代码:
$html="<html><body><p>This is array.</p><br></body></html>";
libxml_use_internal_errors(true);
$dom = New DOMDocument();
$dom->loadHTML($html);
if (empty(libxml_get_errors())) {
echo "This is a good HTML";
} else {
echo "This not html";
}
输出
This is a good HTML
其他方式
您可以使用simplexml_load_string
也验证你的 html,就像这个例子:
function check($string){
$start = strpos($string, '<');
$end = strrpos($string, '>', $start);
if ($end !== false) {
$string = substr($string, $start);
} else {
$string = substr($string, $start, strlen($string) - $start);
}
$string = "<div>$string</div>";
libxml_use_internal_errors(true);
libxml_clear_errors();
simplexml_load_string($string);
return count(libxml_get_errors()) == 0;
}
$html="<html><body><p>This is array.</p></body></html>";
if (check($html)) {
echo "This is a good HTML";
} else {
echo "This not html";
}
但是这种方式有一个问题,例如如果您有 <br>
代码中的标记会返回 false,因此我建议使用第一种更好的方法
关于php - 有没有办法检测字符串在 PHP 或 symfony 中是否具有有效的 HTML 语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65393433/