blake305
blake305

Reputation: 2236

Regex not working properly

Here is my code:

<?php
$text='<td valign="top">text</td><td>more text</td>';
preg_match('/<td valign="?top"?>.*<\/td>)/s', $text, $matches);

?>

$matches[0] should return<td valign="top">text</td> but it returns <td valign="top">text</td><td>more text</td>. Why?

Upvotes: 0

Views: 65

Answers (3)

hakre
hakre

Reputation: 197659

Make the .* pattern un-greedy by adding a ?:

preg_match('/<td valign="?top"?>.*?<\/td>)/s', $text, $matches);
                                ^^^ 

Here is an example of greedy vs. non-greedy regex: http://www.exampledepot.com/egs/java.util.regex/Greedy.html

Why?

That is how regex work. You might be looking for an XML Parser instead:

$text='<td valign="top">text</td><td>more text</td>';

$xml = simplexml_load_string("<x>$text</x>");
list($td) = $xml->xpath('td[@valign="top"]');
echo $td->asXML(); # <td valign="top">text</td>

Upvotes: 4

theHack
theHack

Reputation: 2014

try this <td valign.+?\/td> I think it works

Upvotes: 0

Cybercartel
Cybercartel

Reputation: 12592

? cannot stand alone. It's a modifier and greedy operator. It means looking for the closest match. Maybe you need a .+? in you expression.

Upvotes: 0

Related Questions