[PHP/REGEXP] Afbeeldingen plus afmetingen vinden

Pagina: 1
Acties:

Onderwerpen


Acties:
  • 0 Henk 'm!

  • Slagroom
  • Registratie: Juni 2001
  • Laatst online: 05-10-2024
Hallo,

Ik heb een stukje code geschreven waarmee ik alle afbeeldingen in een stukje HTML kan vinden en daaruit weer de breedte, hoogte en source uit kan filteren.

Dit is de code:
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
preg_match_all("/\< *[img][^\>]*[.]*\>/i", $string, $matches);

foreach($matches[0] as $match)
{
    preg_match("/src=\s*[\"\']{0,1}([^\"\'\ \>]*)/i", $match, $m);
    $src = $m[1];
    
    preg_match("/width[=:]\s*[\"\']?([0-9]*)/i", $match, $m);
    $width = $m[1];
    
    preg_match("/height[=:]\s*[\"\']?([0-9]*)/i", $match, $m);
    $height = $m[1];
    
    $images[] = array(
        'tag' => $match,
        'src' => $src,
        'width' => $width,
        'height' => $height
    );
}


Volgens mij kan dit beter en zijn de vier regexp's te combineren. Ik heb al menig uurtje op het internet rond gezocht maar kan geen info vinden, ook uit de manuals over regular expressions wordt ik niet veel wijzer.

Wie kan mij helpen met het optimalizeren van deze code?

Thanks!

Acties:
  • 0 Henk 'm!

  • Janoz
  • Registratie: Oktober 2000
  • Laatst online: 21-09 02:21

Janoz

Moderator Devschuur®

!litemod

Waarom zou het beter zijn om de 4 regexpen te combineren? Het lijkt mij eerder dat je code daar slechter (want onleesbaarder en waarschijnlijk ook foutgevoeliger) van wordt.

Ken Thompson's famous line from V6 UNIX is equaly applicable to this post:
'You are not expected to understand this'


Acties:
  • 0 Henk 'm!

Verwijderd

Denk dat het makkelijker en sneller is om daar een dom reader voor te gebruiken.
(http://www.ibm.com/developerworks/library/os-xmldomphp/)

Acties:
  • 0 Henk 'm!

  • kluyze
  • Registratie: Augustus 2004
  • Niet online
Ik zou ook willen voorstellen om een dom reader of iets met xml. Maar dat is afhankelijk van hoe betrouwbaar de input html code is.

Acties:
  • 0 Henk 'm!

  • Wassasin
  • Registratie: April 2002
  • Laatst online: 24-03-2024

Wassasin

Hippe kip

You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. As I have answered in HTML-and-regex questions here so many times before, the use of regex will not allow you to consume HTML. Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing HTML. You will never make me crack. HTML is a language of sufficient complexity that it cannot be parsed by regular expressions. Even Jon Skeet cannot parse HTML using regular expressions. Every time you attempt to parse HTML with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing HTML with regex summons tainted souls into the realm of the living. HTML and regex go together like love, marriage, and ritual infanticide. The <center> cannot hold it is too late. The force of regex and HTML together in the same conceptual space will destroy your mind like so much watery putty. If you parse HTML with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes. HTML-plus-regexp will liquify the n​erves of the sentient whilst you observe, your psyche withering in the onslaught of horror. Rege̿̔̉x-based HTML parsers are the cancer that is killing StackOverflow it is too late it is too late we cannot be saved the trangession of a chi͡ld ensures regex will consume all living tissue (except for HTML which it cannot, as previously prophesied) dear lord help us how can anyone survive this scourge using regex to parse HTML has doomed humanity to an eternity of dread torture and security holes using regex as a tool to process HTML establishes a breach between this world and the dread realm of c͒ͪo͛ͫrrupt entities (like SGML entities, but more corrupt) a mere glimpse of the world of reg​ex parsers for HTML will ins​tantly transport a programmer's consciousness into a world of ceaseless screaming, he comes, the pestilent slithy regex-infection wil​l devour your HT​ML parser, application and existence for all time like Visual Basic only worse he comes he comes do not fi​ght he com̡e̶s, ̕h̵i​s un̨ho͞ly radiańcé destro҉ying all enli̍̈́̂̈́ghtenment, HTML tags lea͠ki̧n͘g fr̶ǫm ̡yo​͟ur eye͢s̸ ̛l̕ik͏e liq​uid pain, the song of re̸gular exp​ression parsing will exti​nguish the voices of mor​tal man from the sp​here I can see it can you see ̲͚̖͔̙î̩́t̲͎̩̱͔́̋̀ it is beautiful t​he final snuffing of the lie​s of Man ALL IS LOŚ͖̩͇̗̪̏̈́T ALL I​S LOST the pon̷y he comes he c̶̮omes he comes the ich​or permeates all MY FACE MY FACE ᵒh god no NO NOO̼O​O NΘ stop the an​*̶͑̾̾​̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨe̠̅s ͎a̧͈͖r̽̾̈́͒͑e n​ot rè̑ͧ̌aͨl̘̝̙̃ͤ͂̾̆ ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ

(Schaamteloze copypasta van dit bericht)

Acties:
  • 0 Henk 'm!

  • Slagroom
  • Registratie: Juni 2001
  • Laatst online: 05-10-2024
Hahahaha! Duizend maal excuses! Ik zal dit soort vragen nooit meer stellen ;)

Bedankt voor de opheldering!

Acties:
  • 0 Henk 'm!

  • ValHallASW
  • Registratie: Februari 2003
  • Niet online
@Wassasin: je bent alleen de laatste regel vergeten te kopiëren ;-):
Have you tried using an XML parser instead?
@Slagroom: Niets mis met het stellen van zulke vragen. Je weet nu dat je de volgende keer html niet met regexp's moet parsen - en daarmee ben je een betere programmeur geworden! :-)

Acties:
  • 0 Henk 'm!

  • crisp
  • Registratie: Februari 2000
  • Laatst online: 00:44

crisp

Devver

Pixelated

ValHallASW schreef op woensdag 08 september 2010 @ 19:07:
@Wassasin: je bent alleen de laatste regel vergeten te kopiëren ;-):
[...]
Een XML parser is per definitie niet geschikt voor het parsen van HTML (en zelfs niet voor XHTML - 90% van alle zogenaamde XHTML op het web is mallformed XML) ;)
@Slagroom: Niets mis met het stellen van zulke vragen. Je weet nu dat je de volgende keer html niet met regexp's moet parsen - en daarmee ben je een betere programmeur geworden! :-)
Voor het matchen van losse tags kan je op zich prima reguliere expressies gebruiken, met dien verstande dat bij invalide HTML je waarschijnlijk onverwachte resultaten krijgt. Maar ook een echte parser moet in die gevallen een beroep doen op error-correctie. Het matchen van attributen is vaak wat trickier, maar zelfs daar schrik ik soms niet terug voor een reguliere expressie (als ik tenminste bepaalde verwachtingen mag hebben van de HTML zelf).

Ergo: stellen dat reguliere expressies nooit geschikt zijn om HTML te 'parsen' is wel erg zwart-wit gesteld. Legio echte parsers die ik onder ogen heb gekregen maakten wel op een of andere manier gebruik van reguliere expressies, zij het vaak op een heel simpel niveau.

Intentionally left blank


Acties:
  • 0 Henk 'm!

  • NMe
  • Registratie: Februari 2004
  • Laatst online: 09-09 13:58

NMe

Quia Ego Sic Dico.

De oplossing uit de topicstart is misschien niet ideaal maar wel afdoende voor dit specifieke probleem. Je wil het inderdaad absoluut niet in één regexp doen, maar eerst alle images ophalen en dan daar doorheen lopen voor de attributen is best acceptabel.

'E's fighting in there!' he stuttered, grabbing the captain's arm.
'All by himself?' said the captain.
'No, with everyone!' shouted Nobby, hopping from one foot to the other.


Acties:
  • 0 Henk 'm!

  • FragFrog
  • Registratie: September 2001
  • Laatst online: 22:47
Verwijderd schreef op dinsdag 07 september 2010 @ 21:08:
Denk dat het makkelijker en sneller is om daar een dom reader voor te gebruiken.
Hier wil ik me bij aansluiten.

Niets ten nadele van de heren in rood hierboven, maar regexpen zijn hier nodeloos complex en foutgevoelig. Ter illustratie, hoe je zoiets bijvoorbeeld met een DOMDocument kan oplossen:
PHP:
1
2
3
4
5
6
7
8
9
10
11
$document     =   new DOMDocument();
$document    ->   loadHTML($htmlString);
$images       =   $document -> getElementsByTagName('img');
$properties   =   array();

foreach ($images as $image) {
  $details = array('src'    =>  $image -> getAttribute('src'),
                   'width'  =>  $image -> getAttribute('width'),
                   'height' =>  $image -> getAttribute('height'));
  $properties[] = $details;
}

Simpel, kort en robuust :)

[ Site ] [ twitch ] [ jijbuis ]


Acties:
  • 0 Henk 'm!

  • ValHallASW
  • Registratie: Februari 2003
  • Niet online
Ik had FragFrog's post in python geïmplementeerd, maar dat voegde weinig toe

@Hierboven: Dat doet alleen niet precies hetzelfde. Het match bijvoorbeeld geen marquee-tags. Ook geen i-tags, en zelfs geen multicol-tags. Maar dat was geloof ik ook eigenlijk niet wat de TS wilde.

Dat niemand anders (waaronder de mensen uit het pro-regexp-kamp) dat is opgevallen zegt al genoeg over regexps: lozen die handel, tenzij je zwaarwegende redenen hebt om ze wel te gebruiken.

Ohja, die loop is trouwens ook niet echt meer nodig:
PHP:
1
2
3
4
<?php 
$document     =   new DOMDocument(); 
$document    ->   loadHTML($htmlString); 
$images       =   $document -> getElementsByTagName('img');


is eigenlijk al equivalent. Toegegeven, je moet dan wel in je code $image->src doen ipv $image['src'], maar dat lijkt me (in ieder geval voor de volgende keer ;-)) geen onoverkomelijk probleem.

En, als je het echt kort wilt hebben:
PHP:
1
$images = DOMDocument::loadHTML($htmlString)->getElementsByTagName('img');

[ Voor 84% gewijzigd door ValHallASW op 08-09-2010 20:29 ]


Acties:
  • 0 Henk 'm!

  • Voutloos
  • Registratie: Januari 2002
  • Niet online
Jep, het '[img]' deel is inderdaad al een prima bug. ;)

{signature}

Pagina: 1