を使用して、ノード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";
}
このデモでは、すべてのテストに合格していることがわかります。次の要件を満たしています。
<p>
タグ内の画像とテキストのみ。その他のタグは無効です。これが正しくない場合は、必要に応じて変更してください。
- テキストがある場合、
<img>
タグを検出する前にテキストが来る必要があります。