开发者

Regex not working properly

开发者 https://www.devze.com 2023-03-27 12:31 出处:网络
Here is my code: <?php $text=\'<td valign=\"top\">text</td><td>开发者_StackOverflow中文版more text</td>\';

Here is my code:

<?php
$text='<td valign="top">text</td><td>开发者_StackOverflow中文版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?


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>


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消