goni
goni

Reputation: 1

preg_match_all not work

preg_match_all('/<img(.*)width="9" height="9" alt="(.*)" title="" />/' , $html , $sources );
foreach($sources[1] as $alt){
echo $alt."<br\>";
}

I want to list all alt tags values matched from a html page in all image whats wrong?

I want to use regex not dom.

Upvotes: 0

Views: 2968

Answers (4)

Pedro Lobito
Pedro Lobito

Reputation: 98881

you're just being stubborn, use PHP Simple HTML DOM Parser, or similar, to parse html.

ex:

// Create DOM from URL or file
include('simple_html_dom.php');
$html = file_get_html('http://www.scroogle.org/');

    // Find all images
    foreach($html->find('img') as $element)
           echo $element->src . '<br>';
           echo $element->alt. '<br>';

Upvotes: 0

mario
mario

Reputation: 145482

Well, without knowing the exact html source, hard to tell. But there are multiple issues, and a good example why newcomers should not use regular expressions for that purpose:

  • It will only ever match if the HTML attributes occur in this very particular order.
  • Should the alt= and title= tags be switched in the souce, it will fail.
  • Should the tag not end with the redundant />, it will also not match.
  • It can only detect the strings in the source if there is always exactly one space between the attributes. If there is a line-break in your HTML source, or a tab somewhere, or two spaces, ... (see \s*)
  • The (.*) should be (.*?) in any case. Preferrably however one uses [^>]+ or [^"]+ for this use.
  • The #e eval flag has no use in preg_match_all.

Upvotes: 0

mravey
mravey

Reputation: 4500

You need to escape the / of the img tag :

preg_match_all('/<img(.*)width="9" height="9" alt="(.*)" title="" \/>/' , $html , $sources );

Otherwise it is considered as the end of your refex.

Upvotes: 0

daschl
daschl

Reputation: 1124

Please consult the php documentation for a correctpreg_match_all call. You need to provide regex delimiters!

Also, your problem description is not very specific so if you want any more help you'll need to rewrite your question posting.

Upvotes: 1

Related Questions