how I can check if there are img tags only in a paragraph or or at the end of the paragraph?
$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) { ... };
Any other better methods than preg_match
and regex
?
You can use DOMDocument
, and check if there are any text contents on the <p>
node:
$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' . "
";
} else {
echo 'NOT ok' . "
";
}
You can see in this demo that is passes all of your tests. It fulfills the requirements:
<p>
tag. Any other tags, are invalid. If this is untrue, modify it for your needs.<img>
tag.Try this regular expression:
/<p[^>]*>.*<img[^>]*></p>/
Explanation: If you want to match a tag with unknown attributes with regex you can use <TAGNAME[^>]*>
. The expression [^>]*
matches every character zero or n times besides >
, thus accepting any numbers of attributes.
Use this one:
if (preg_match("/<img\s[^<>]*><\/p>/i", $input) { ... };