2012-12-27 86 views
1

我想問一下如何從字符串中刪除一個特殊字符(從廢棄頁面中提取)。刪除字符串中不需要的字符

 4:30am 

我只是想使我用盡所以時間使用此過濾它:

$str = 'Â 4:30am'; 
$new_string = preg_replace("[^A-Za-z0-9]", "", $str); 
echo '<pre>'.$new_string.'</pre>'; 

但它不會改變:| 有沒有解決方案/方法?

回答

7

你的正則表達式是無效...

$str = 'Â 4:30am'; 
$new_string = preg_replace("~[^a-z0-9:]~i", "", $str); 
echo '<pre>'.$new_string.'</pre>'; 

...你忘了 「:」 在正則表達式,所以你的情況將被刪除。

+0

謝謝你的父親:)得到它! – Vainglory07

3

使用$new_string = preg_replace("/[^A-Za-z0-9]/", "", $str);應該修復它。

preg_replace的第一個參數是需要被類似/@的東西包圍的模式。

在你的情況,你使用的模式[^A-Za-z0-9]其中[]被視爲模式分隔符。所以匹配的實際模式變成^A-Za-z0-9,它與輸入中的任何內容都不匹配。

1

要獲取時間:

$str = 'Â 4:30am'; 
$time = preg_match('/(?P<time>\d?\d:\d\d(?:am|pm))/', $str, $match); 
var_dump($match); 
1

試試這個

$new_string = preg_replace("^[A-Za-z0-9]", "", $str); 
0
$str = 'Â 4:30am'; 
$new_string = preg_replace("^\W", "", $str); 
echo '<pre>'.$new_string.'</pre>'; 
+0

簡單而好 –

+0

缺少分隔符,即使在添加分隔符後也不起作用。 –

3

您可以使用filter_var

$str = 'Â 4:30am'; 
$str = filter_var($str,FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_HIGH); 
echo $str ; 

輸出

4:30am 
+0

真棒@Baba! – Vainglory07