如何从正在变化的字符串值中获取特定数字; php

how to get specific numbers out of string value that is changing ; php

我正在尝试从位置信息字符串中获取纬度和经度数值。

如果我在地图上搜索 'hawaii',地图 api returns 字符串值如下所示。

$location = {地图: geo="20.471884,-157.505,6" p="Hawaii"}

我想将纬度和经度值转换为 $lat、$lng。

我怎样才能在 php 内完成???

也许您需要这样的东西:

<?php

$re = '/(["\'])(\\?.)*?/';
$str = '{map: geo="20.471884,-157.505,6" p="Hawaii"}';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches);

在这里测试:http://sandbox.onlinephpfunctions.com/code/e858fca9b0ba65d59919f28ae2a228db5e7610da

如果您不想在之后没有 ,6 的情况下匹配该模式,您可以使用:

^{map:\h+geo="(?P<lat>-?\d+(?:\.\d+)?)(?:,\d+)?,(?P<lon>-?\d+(?:\.\d+)?)(?:,\d+)?"[^}]+}

说明

  • ^{map:\h+geo= 字符串开头,匹配 {map: 和 1+ 个水平空格和 geo="
  • (?P<lat> 命名捕获组 lat
    • -?\d+匹配可选-, 1+位
    • (?:\.\d+)? . 和 1+ 位
    • 的可选部分
  • ) 关闭群组
  • (?:,\d+)? , 和 1+ 位
  • 的可选部分
  • , 值之间的逗号
  • (?P<lon> 命名捕获组 lon
    • -?\d+匹配可选-, 1+位
    • (?:\.\d+)? . 和 1+ 位
    • 的可选部分
  • ) 关闭群组
  • (?:,\d+)? , 和 1+ 位
  • 的可选部分
  • "[^}]+}匹配"然后直到结束}

Regex demo | Php demo

例如

$re = '/^{map:\h+geo="(?P<lat>-?\d+(?:\.\d+)?)(?:,\d+)?,(?P<lon>-?\d+(?:\.\d+)?)(?:,\d+)?"[^}]+}/';
$str = '{map: geo="20.471884,-157.505,6" p="Hawaii"}';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

$lat = $matches[0]["lat"];
$lon = $matches[0]["lon"];

echo $lat; // 20.471884
echo PHP_EOL;
echo $lon; // -157.505

您可以通过使用 (?1)

递归第一个子模式来稍微缩短模式
^{map:\h+geo="(?P<lat>-?\d+(?:\.\d+)?)(?:,\d+)?,(?P<lon>(?1))(?:,\d+)?"[^}]+}