Hãy thử:
preg_match_all('/\w+:\s*(-?\d+\.\d+),(-?\d+\.\d+)/',
"iPhone: 52.973053,-0.021447 FOO: -1.0,-1.0",
$matches, PREG_SET_ORDER);
print_r($matches);
trong đó sản xuất:
Array
(
[0] => Array
(
[0] => iPhone: 52.973053,-0.021447
[1] => 52.973053
[2] => -0.021447
)
[1] => Array
(
[0] => FOO: -1.0,-1.0
[1] => -1.0
[2] => -1.0
)
)
Hoặc chỉ:
preg_match('/\w+:\s*(-?\d+\.\d+),(-?\d+\.\d+)/',
"iPhone: 52.973053,-0.021447",
$match);
print_r($match);
nếu chuỗi chỉ chứa một tọa độ.
Một lời giải thích nhỏ:
\w+ # match a word character: [a-zA-Z_0-9] and repeat it one or more times
: # match the character ':'
\s* # match a whitespace character: [ \t\n\x0B\f\r] and repeat it zero or more times
( # start capture group 1
-? # match the character '-' and match it once or none at all
\d+ # match a digit: [0-9] and repeat it one or more times
\. # match the character '.'
\d+ # match a digit: [0-9] and repeat it one or more times
) # end capture group 1
, # match the character ','
( # start capture group 2
-? # match the character '-' and match it once or none at all
\d+ # match a digit: [0-9] and repeat it one or more times
\. # match the character '.'
\d+ # match a digit: [0-9] and repeat it one or more times
) # end capture group 2
Nguồn
2010-04-06 13:49:38
Tôi tự hỏi nếu nó thực sự cần thiết để phù hợp với chữ số? Có thể đơn giản hơn nhiều để phân chia ở dấu hai chấm và dấu phẩy? (xin lỗi cho tôi nếu điều này là câm ;-) –
Đó là một lựa chọn nếu chuỗi sẽ luôn luôn trông như thế. Nhưng có lẽ đầu vào thay đổi một chút hoặc kết hợp cũng được sử dụng để xác nhận. –