2013-08-20 120 views
0

我使用商店的座標並手動將座標作爲lang和long添加到數據庫。有時候會錯誤地批准座標。preg替換爲所需值

讓我舉個例子來說吧。

例如; 朗33.4534543543錯誤。但有時我把鍵盤和它變得像,

33.4534543543< 

或 33.4534543543, 或 ,(空間)33.4534543543 <

我怎樣才能得到只有33.4534543543?

+0

簡單情況:?'/ \ d * \ \ d +/g' –

+0

你有什麼tryed這麼遠嗎?你爲什麼要手動輸入這些? cpoy /粘貼? –

+0

「lang and long」?你不是說「經緯度」嗎? –

回答

0

preg_match_all

要找到包含多個匹配的字符串匹配,你可以使用preg_match_all

$strings = "33.4534543543< 
33.4534543543, 
, 33.4534543543<"; 
$pattern = "!(\d+\.\d+)!"; 

preg_match_all($pattern,$strings,$matches); 

print_r($matches[0]); 

輸出

Array 
(
    [0] => 33.4534543543 
    [1] => 33.4534543543 
    [2] => 33.4534543543 
) 

的preg_match

要找到可以使用preg_match一個字符串匹配。

$string = "33.4534543543<"; 
$pattern = "!(\d+\.\d+)!"; 

if(preg_match($pattern,$string,$match)){ 
print($match[0]); 
} 

輸出

33.4534543543 

的preg_replace

要更換什麼,是不是你現有的字符串中想你會使用preg_replace什麼:

$string = preg_replace('![^\d.]!','',$string); 

一個例子:

$strings = "33.4534543543< 
33.4534543543, 
, 33.4534543543<"; 

$strings_exp = explode("\n",$strings); 

$output = ''; 
foreach($strings_exp as $string){ 
$output.= "String '$string' becomes "; 
$new_string = preg_replace('![^0-9.]!','',$string); 
$output.= "'$new_string'\n"; 
} 

echo $output; 

輸出

String '33.4534543543<' becomes '33.4534543543' 
String '33.4534543543,' becomes '33.4534543543' 
String ', 33.4534543543<' becomes '33.4534543543' 
0

聽起來像你想要做一個preg_matchhttp://phpfiddle.org/main/code/z6q-a1d

$old_vals = array(
    '33.4534543543<', 
    '33.4534543543,', 
    ', 33.4534543543<' 
); 

$new_vals = array(); 

foreach ($old_vals as $val) { 
    preg_match('(\d*\.?\d+)',$val, $match); 
    array_push($new_vals, $match[0]); 
} 

print_r($new_vals); 

輸出

Array (
    [0] => 33.4534543543, 
    [1] => 33.4534543543, 
    [2] => 33.4534543543 
)