2013-08-20 22 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 
)