0

After viewing some answers on stackoverflow,

preg_match_all('/<img[^>]+>/i',$html, $result);
$img = array();
foreach( $result[0] as $img_tag)
{
    preg_match_all('/(title)=("[^"]*")/i',$img_tag, $img[$img_tag]);
}

//print_r($img);
foreach ($img as $imgg)
 echo $imgg[2][0];

The above code finds img title, but however it return as "Waterfall fountain" instead of Waterfall fountain, notice there is "

what should i add in regex to remove "?

Thank you

1
  • 2
    Apparently not enough answers... the subject is beaten to fine ash. PHP has an HTML parser, which will do a better than a regex. Commented Jul 29, 2010 at 14:17

6 Answers 6

3

Just move the " out of the capturing group:

'/(title)="([^"]*)"/i'
Sign up to request clarification or add additional context in comments.

1 Comment

If you are dealing with legacy code that doesn't surround attributes with quotes, use this: '/(title)="?([^" ]*)"?/i' It also works if the quoted value does NOT contain a space
1

move the quotes outside of your brackets

preg_match_all('/(title)="([^"]*)"/i',$img_tag, $img[$img_tag]); 

Comments

1

Use an XML Parser and this XPath to get all titles of img elements:

//img/@title

Example with DOM

$dom = new DOMDocument;
$dom->loadHML($html);
$xp = new DOMXPath($dom);
foreach($xp->query('//img/@title') as $attribute) {
    echo $attribute->nodeValue;
}

Further readings:

Comments

1

Move the quotes outside of your brackets.

Check this :

preg_match_all('/(title)="([^"]*)"/i',$img_tag, $img[$img_tag]); 

Comments

0

Currently you are making the " part of the match that is remembered. You can put the quotes outside the parenthesis:

preg_match_all('/(title)="([^"]*)"/i',$img_tag, $img[$img_tag]);

Comments

0

Parentheses in a regular expression make a capturing group, which control what get stored in $img[$img_tag]. Your group included the quotes: ("[^"]*"). If you don't want the quotes, just move them outside the group: "([^"]*)"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.