2015-05-04 123 views
1

我需要在php字符串中第一次出現數字後刪除所有內容,但要保留數字。我無法保留該號碼:當我寫這個在第一次出現數字後刪除所有內容php

preg_replace('/[0-9].*/', '', $string); 

它刪除包括數字在內的所有信息。我的另一個問題是字符串是希伯來語我試圖使用這個功能:

$count = mb_strlen($string,'UTF-8'); 
$i = 0; 
while($i < $count) { 
    if(ctype_digit($string[$i])) { 
     echo "First digit found at position $i."; 
     return; 
    } 
    $i++; 
} 

但它也行不通。任何幫助?

+0

中有什麼'$ string'? –

+0

這是一個帶數字的希伯來字符串。 –

回答

5

如果你的第一個替換已經工作,但去除太多,你可以捕獲的數量,並把它放回:

preg_replace('/([0-9]+).*/', '$1', $string); 
      ^ ^  ^^ put the captured value back 
2

在你的while循環中,嘗試使用mb_substr($string, $i, 1)獲得字符而不是$string[$i]。我認爲後者只返回字節索引$ i的單個字節,而不是多字節字符串中的$ i字符。

0

示例代碼:

$str = "abc123efg567jjjj"; 
echo preg_replace("/([^0-9]*[0-9]*)(.*)/", "$1", $str); 

輸出示例:

abc123 
相關問題