PDA

Archiv verlassen und diese Seite im Standarddesign anzeigen : Tags samt Attributen aus HTML filtern


pleini
31.08.2007, 12:13
Hallo!

Ich möchte mit PHP eine Funktion bauen, die aus einem HTML-Code

z.B.

<html>
<body>
<table border="0">
<tr><td><img src="bild.gif" alt="bild" width="300"></td></tr></table>
<img src="test.jpg" alt="test" height="400" />
</body>
</html>
alle gesuchten Tags (z.B. img) samt Attributen als Array auslesen.
Also beispielsweise search("img") liefert ein

Array {
[0]["full_tag"] => "<img src="bild.gif" alt="bild" width="300">"
["src"] => "bild.gif"
["alt"] => "bild"
["width"] => 300
[1]["full_tag"] => "<img src="test.jpg" alt="test" height="400" />"
["src"] => "test.jpg"
["alt"] => "test"
["height"] => 400
}
, wobei search("table") entsprechend dieses

Array {
[0]["full_tag"] => "<table border="0">"
["border"] => 0
}
liefert.

Das Ganze sollte auch mit XHTML funktionieren.
Ich habe jetzt schon recht lange gegoogelt und im Forum gesucht, aber leider nichts gefunden.

Habt ihr ne Idee?

Gruß pleini!


eViL_oNe
31.08.2007, 14:30
wenn es nicht unbedingt regex sein muss: das Document Object Model ist hier das Zauberwort:

http://de2.php.net/DOM

pleini
31.08.2007, 15:23
Danke, ich hab es jetzt mal gelöst und des funktioniert.

Kann man sicherlich noch optimieren. Falls es jemand haben möchte - hier meine Lösung:


// Returns all tags with attributes out of a html source code as an array
function filter_tag($source_code, $tag = "img")
{
$pattern_tags = '~<'.$tag.'(?:[\s\w]+=(?:\w+|"[^"]+"|\'[^\']+\'))*\s*/?>~';
$pattern_tags = "/<img [^>]*>/i";
$pattern_attributes = "/([a-zA-Z]*)[=|[:space:]=|=[:space:]|[:space:]=[:space:]]{1}[\"|'](.*?)[\"|']/i";
preg_match_all($pattern_tags, $source_code, $match_tags);

$tags = array();
$i = 0;
// All Tags
foreach($match_tags[0] as $ergebnis_tags)
{
$tags[$i]["full_tag"] = $ergebnis_tags;
$tags[$i]["tag"] = $tag;

preg_match_all($pattern_attributes, $ergebnis_tags, $match_attributes);
array_shift($match_attributes);

// All attributes in a tag
for($x=0;$x<count($match_attributes[0]);$x++)
{
$tags[$i][$match_attributes[0][$x]] = $match_attributes[1][$x];
}
$i++;
}

return $tags;
}

eViL_oNe
01.09.2007, 13:23
jo, so geht's natürlich auch -- is halt mehr low level und fehleranfälliger *g*

mit DOM würde man im Prinzip durch den Tree traversieren und alle Tags sich merken, die dem eingegebenen entsprechen. Eigentlich ne Programmierarbeit von 30 Minuten ;)