preg_replace表示所需的值

时间:2013-08-20 19:51:23

标签: php regex preg-replace

我使用商店的坐标并手动将坐标添加为lang和long到数据库。有时是错误的,批准坐标。

让我以一个例子来表达。

例如; Lang是33.4534543543。但是有时我会推动键盘,它变得像,

33.4534543543<

或     33.4534543543, 要么     ,(空间)33.4534543543&LT;

我怎样才能获得33.4534543543?

2 个答案:

答案 0 :(得分: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
)

答案 1 :(得分: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'