2012-11-24 494 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); 

希望有所幫助。

相關問題