0

如何检查是否仅在段落中或段落末尾有 img 标签?

$input = '<p><img src="#" /></p>'; // ok
$input = '<p><img src="#" /><img src="#" /></p>'; // ok
$input = '<p>xxx<img src="#" /></p>'; // ok

$input = '<p><img src="#" />xxx</p>'; // NOT ok

if(preg_match("/img/$", $input) { ... };

还有比preg_matchand更好的方法regex吗?

4

3 回答 3

3

您可以使用, 并检查节点DOMDocument上是否有任何文本内容:<p>

$doc = new DOMDocument;
$doc->loadHTML( $input);

$p = $doc->getElementsByTagName('p')->item(0);
$children = $p->childNodes;

$img_found = false; $error = false;

foreach( $children as $child) {
    if( $child->nodeType == XML_TEXT_NODE && !$img_found) {
        // Text before the image, OK, continue on
        continue;
    }
    if( $child->nodeType == XML_ELEMENT_NODE) {
        // DOMElement node
        if( !($child->tagName == 'img')) {
            // echo "Invalid HTML element found";
            $error = true;
        } else {
            $img_found = true;
        }
    } else {
        // echo "Invalid node type!";
        $error = true;
    }
}

// No errors and we found at least one image, we're good
if( $img_found && !$error) {
    echo 'ok' . "\n";
} else {
    echo 'NOT ok' . "\n";
}

您可以在此演示中看到它通过了所有测试。它满足以下要求:

  1. <p>标签内只有图像和文本。任何其他标签均无效。如果这是不正确的,请根据您的需要进行修改。
  2. 如果有文本,它必须在我们检测到<img>标签之前出现。
于 2012-11-15T14:31:23.223 回答
1

试试这个正则表达式:

/<p[^>]*>.*<img[^>]*></p>/

说明:如果您想用正则表达式匹配具有未知属性的标签,您可以使用<TAGNAME[^>]*>. 该表达式[^>]*匹配除 之外的每个字符 0 次或 n 次>,因此接受任意数量的属性。

于 2012-11-15T14:31:54.050 回答
1

使用这个:

if (preg_match("/<img\s[^<>]*><\/p>/i", $input) { ... };
于 2012-11-15T15:14:19.320 回答