2012-11-24 457 views
-1

我想从一组循环中运行的字符串中删除所有括号。我所见过的最好的方法是使用preg_replace()。但是,我很难理解模式参数。删除字符串中的括号

以下是循环

$coords= explode (')(', $this->input->post('hide')); 
     foreach ($coords as $row) 
     { 
      $row = trim(preg_replace('/\*\([^)]*\)/', '', $row)); 
      $row = explode(',',$row); 
      $lat = $row[0]; 
      $lng = $row[1]; 
     } 

这是“隐藏”的价值。

(1.4956873362063747, 103.875732421875)(1.4862491569669245, 103.85856628417969)(1.4773257504016037, 103.87968063354492) 

就我所知,这种模式是错误的。我从另一个线程得到它,我试图阅读有关模式,但无法得到它。我的时间很短,所以我在这里发布了这个消息,同时还在网络的其他部分寻找其他方式。有人可以提供我正在尝试做的正确模式吗?或者有更简单的方法来做到这一点?

编辑:啊,刚刚得到preg_replace()如何工作。显然我误解了它的工作原理,谢谢你的信息。

+1

'$ this-> input-> post('hide')'' – Ravi

+0

'如何使用'preg_replace('#[()]#',“”,$ this-> input-> post('hide'))' –

+0

发布你想要的输出的例子 – dynamic

回答

0

“这是$ coords的价值。”

如果$ coords是一个字符串,那么您的foreach就没有意义了。如果该字符串为您的输入,然后:

$coords= explode (')(', $this->input->post('hide')); 

这条线将删除你的字符串内括号,所以你的$ COORDS阵列将是:

  • (1.4956873362063747,103.875732421875
  • 1.4862491569669245,103.85856628417969
  • 1.4773257504016037,103.87968063354492)
0

pattern参数接受正则表达式。该函数返回一个新字符串,其中与正则表达式匹配的所有原始部分都被第二个参数替换,即replacement

如何在原始字符串上使用preg_replace

preg_replace('#[()]#',"",$this->input->post('hide')) 

要剖析当前的正则表达式,你匹配:

an asterisk character, 
followed by an opening parenthesis, 
followed by zero or more instances of 
    any character but a closing parenthesis 
followed by a closing parenthesis 

当然,这永远不会匹配,因为爆炸的字符串移除了大块的关闭和开启括号。

1

我看出来你真的要提取所有坐标

如果是这样,更好地利用preg_match_all:

$ php -r ' 
preg_match_all("~\(([\d\.]+), ?([\d\.]+)\)~", "(654,654)(654.321, 654.12)", $matches, PREG_SET_ORDER); 
print_r($matches); 
' 
Array 
(
    [0] => Array 
     (
      [0] => (654,654) 
      [1] => 654 
      [2] => 654 
     ) 

    [1] => Array 
     (
      [0] => (654.321, 654.12) 
      [1] => 654.321 
      [2] => 654.12 
     ) 

) 
1

我并不完全明白你为什么会需要preg_replaceexplode()删除了分隔符,因此,您只需分别删除第一个和最后一个字符串的开启和关闭的缺口即可。你可以使用substr()

获得第一和数组的最后元素:

$first = reset($array); 
$last = end($array); 

希望有所帮助。

相关问题