preg_match coordinates with degree sign

╄→尐↘猪︶ㄣ 提交于 2019-12-08 04:00:55

问题


I am trying to capture the coordinates of an input that could look like this

22°50'23.46"S, 43° 0'44.80"W

or this

41°12'27.84"N, 16°18'40.15"E

I think the problem is the degree symbols in my pattern. My current code:

$found = preg_match("~(\d+\p{Sm}\d+\s*\'\s*\d+\s*\.\s*\d+\s*\"\s*[N|S])\s*,\s*(\d+\s*\p{Sm}\s*\d+\s*\'\s*\d+\s*\.\s*\d+\s*\"\s*[E|W])~i", $_POST['submission']['url'], $matches);

$matches stays empty.


回答1:


Perhaps you should try ignoring the actual degrees and tick marks and focus just on the data you want to grab.

(\d+)\D+(\d+)\D+(\d+)\.(\d+)\W(\w+)\W+(\d+)\D+(\d+)\D+(\d+)\.(\d+)\W(\w)

This regex should capture the following data:

41
12
27
84
N
16
18
40
15
E

(Edit2: Corrected to properly pick up the N without punctuation.)




回答2:


You're missing the /u modifier to make the engine interpret the pattern as Unicode.




回答3:


What is stopping you from using the ° character literally?

/
  (\d+\s*°\s*  \d+\s*'\s*  \d+\s*\.\s*\d+\s*"\s*  [NS])
  \s*,\s*
  (\d+\s*°\s*  \d+\s*'\s*  \d+\s*\.\s*\d+\s*"\s*  [EW])
/xi



回答4:


Use mb_ereg_match instead to support UTF-8 chars. Docs: http://php.net/manual/en/book.mbstring.php

Initialize mb* like this:

mb_regex_encoding('UTF-8');
mb_internal_encoding('UTF-8');


来源:https://stackoverflow.com/questions/5355874/preg-match-coordinates-with-degree-sign

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