Ja, sollte.
[code]~<img[^>]*>~i
~<a[^>]>.?~is[/code]
Der s-Modifier im zweiten Ausdruck ist wichtig. i ist weniger wichtig, aber bei HTML-Tags ist die Groß- und Kleinschreibung beliebig.
Eingabe:
[php]$input = <<<EOT
Mein Link
Mein
Link
Mein
Link

<img
src=„http://www.example.org/foo.png“
/>
<![CDATA[
]]>


EOT;
#[/php]
Regex:
[php]$pattern = ‚~<img[^>]*>~i‘;
$matches = array();
preg_match_all($pattern, $input, $matches);
var_dump($matches);
$pattern = ‚~<a[^>]>.?~is‘;
$matches = array();
preg_match_all($pattern, $input, $matches);
var_dump($matches);[/php]
[code]$ php -f test.php
array(1) {
[0]=>
array(5) {
[0]=>
string(44) „
“
[1]=>
string(46) "<img
src=„http://www.example.org/foo.png“
/>"
[2]=>
string(30) „
“
[3]=>
string(44) „
“
[4]=>
string(44) „
“
}
}
array(1) {
[0]=>
array(4) {
[0]=>
string(47) „Mein Link“
[1]=>
string(82) "Mein
Link"
[2]=>
string(26) „Not a link“
[3]=>
string(47) „Mein
Link“
}
}
[/code]
DOMDocument:
[php]/**
-
@see http://refactormycode.com/codes/708-innerhtml-of-a-domelement
-
@param $node DOMNode
*/
function innerHTML($node)
{
$doc = new DOMDocument();
foreach ($node->childNodes as $child) {
$doc->appendChild($doc->importNode($child, true));
}
// DOMDocument seems to add a trailing newline, remove that
return substr($doc->saveHTML(), 0, -1);
}
// Suppress „invalid markup“ warnings
libxml_use_internal_errors(true);
$document = new DOMDocument();
$document->loadHTML($input);
$xpath = new DOMXPath($document);
foreach ($xpath->query(‚//a|//img‘) as $node) {
/* @var $node DOMElement */
switch ($node->nodeName) {
case 'a':
echo '------------- Found an a tag. (href='
. $node->getAttribute('href') . ')' . "\n";
echo ' Inner HTML: "' . innerHTML($node) . '"' . "\n";
break;
case 'img':
echo '------------- Found an img tag. (src='
. $node->getAttribute('src') . ')' . "\n";
break;
default:
/* nop */
break;
}
echo "\n";
}[/php]
[code]$ php -f test.php
------------- Found an a tag. (href=http://www.example.org/)
Inner HTML: „Mein Link“
------------- Found an a tag. (href=http://www.example.org/)
Inner HTML: "Mein
Link"
------------- Found an a tag. (href=http://www.example.org/)
Inner HTML: „Mein
Link“
------------- Found an img tag. (src=http://www.example.org/foo.png)
------------- Found an img tag. (src=http://www.example.org/foo.png)
------------- Found an img tag. (src=http://www.example.org/foo.png)
------------- Found an img tag. (src=http://www.example.org/foo.png)
[/code]
Hier wird wohl ersichtlich, dass die regulären Ausdrücke keine exakten Parser sein können.
Edit: in meinem Beispiel ist übrigens tatsächlich kein valides HTML, guck an. 