2010-04-06 47 views
5

我正在認真地努力讓我的頭繞過正則表達式。正則表達式幫助操縱字符串

我有一個SRING與「iPhone:52.973053,-0.021447」

我想結腸成逗號分隔這麼兩個不同的字符串後兩個數字提取。

任何人都可以幫助我嗎?乾杯

回答

2

不使用正則表達式,使用explode()stripos() :)一個解決方案:

$string = "iPhone: 52.973053,-0.021447"; 
$coordinates = explode(',', $string); 
// $coordinates[0] = "iPhone: 52.973053" 
// $coordinates[1] = "-0.021447" 

$coordinates[0] = trim(substr($coordinates[0], stripos($coordinates[0], ':') +1)); 

假設該字符串總是包含一個冒號。

或者,如果冒號前的標識符僅包含字符(不是數字),你可以這樣做也是這個:

$string = "iPhone: 52.973053,-0.021447"; 
$string = trim($string, "a..zA..Z: "); 
//$string = "52.973053,-0.021447" 

$coordinates = explode(',', $string); 
7

嘗試:

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); 

主要生產:

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 
     ) 

) 

或者只是:

preg_match('/\w+:\s*(-?\d+\.\d+),(-?\d+\.\d+)/', 
    "iPhone: 52.973053,-0.021447", 
    $match); 
print_r($match); 

如果字符串只包含一個座標。

一個小的解釋:

\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 
+0

我不知道是否真的有必要,以配合數字?在冒號和逗號分割可能會更簡單嗎? (請原諒我,如果這是愚蠢的;-) – 2010-04-06 13:54:09

+0

這是一個選項,如果字符串總是看起來像那樣。但也許輸入會稍微變化,或者匹配也用於驗證。 – 2010-04-06 13:59:57

0

嘗試:

$string = "iPhone: 52.973053,-0.021447"; 

preg_match_all("/-?\d+\.\d+/", $string, $result); 
print_r($result); 
+0

感謝您的大力幫助,我現在正在努力工作:D – user310070 2010-04-06 15:07:08

0

我喜歡@ Felix的非正則表達式的解決方案,我認爲他的問題的解決方案比使用正則表達式更清晰可讀。

不要忘記,如果原始字符串格式被更改,您可以使用常量/變量來更改通過逗號或冒號分割。

喜歡的東西

define('COORDINATE_SEPARATOR',','); 
define('DEVICE_AND_COORDINATES_SEPARATOR',':'); 
0
$str="iPhone: 52.973053,-0.021447"; 
$s = array_filter(preg_split("/[a-zA-Z:,]/",$str)); 
print_r($s); 
0

甚至更​​簡單的解決方案是用一個更簡單的正則表達式,例如使用使preg_split()

$str = 'iPhone: 52.973053,-0.021447'; 
$parts = preg_split('/[ ,]/', $str); 
print_r($parts); 

,這將給你

Array 
(
    [0] => iPhone: 
    [1] => 52.973053 
    [2] => -0.021447 
)