preg_match_all

旧时模样 提交于 2019-12-08 12:26:48

问题


Could some one explain this to me i am not familiar with preg_match_all filters, this code works fine except it does not return a negative value if one of the latitudes and longitudes is negative.

if ( preg_match_all( "#<td>\s+-?(\d+\.\d+)\s+</td>#", $output, $coords ) ) {
    list( $lat, $long ) = $coords[1];
    echo "Latitude: $lat\nLongitude: $long\n";
}

output: Latitude: 30.6963 Longitude: 71.6207 (longitude is missing a '-')


回答1:


The value of the coords variable depends on what is matched by the code inside the parentheses. Moving the optional minus sign (-?) inside the parentheses should do the trick:

if ( preg_match_all( "#<td>\s+(-?\d+\.\d+)\s+</td>#", $output, $coords ) ) {

See the official documentation for details about preg in php and php.net/preg_match_all for the details of preg_match_all.




回答2:


Your sign is not in the parenthesis. $coords[1] contains the part of the regex that matched the part between ( and ). The +- are before the parenthesis, though, thus they are not part of what is matched and returned.




回答3:


If you don't like preg_match() API, you can use T-Regx tool - it's really cool

$p = "<td>\s+(-?\d+\.\d+)\s+</td>"; // no delimiters :)

pattern($p)->match($output)->forEach(function (Match $match) {
    $match->text();

    // or
    $match->group(1)->text();
    // or check if it's matched
    $match->group(1)->matched();
});


来源:https://stackoverflow.com/questions/586523/preg-match-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!