2012-12-24 83 views
3

我想從DB中搜索文本中的數字並打印它們。數字是產品代碼,從4到6位數不等。搜索字符串(變量匹配)並打印

例子:

aaaaa 1234 aaaa 
aaaaa 123456 aaaaa 
aaaaa 12345 aaaaa 

我什麼是5號的精確匹配的數組,但不能變,不打印:

$string = $sql['products_description']; 
preg_match_all('/(?<![0-9])[0-9]{5}(?![0-9])/', $string, $match); 
for ($i=0; $i<10; $i++) { 
    echo $match[$i]; 
    echo '<br>'; 
} 

任何幫助嗎?

編輯: 我得到這個緊密合作:

$string = $sql['products_description']; 
preg_match_all('#\d{4,6}#', $string, $matches); 
foreach ($matches as $match) { 
    print_r($match); 
} 

但返回類似:

陣列([0] => 1234 [1] => 123456 [2] => 12345)

我純粹需要它們(不是在一個數組中),因爲我必須稍後分別使用每個數字。在這種情況下,如何提取每個元素並將其打印出來?

SOLUTION:

$var = array(); 
preg_match_all('#\d{4,6}#', $string, $matches); 
foreach ($matches as $match) { 
$var[] = $match; 
} 

for ($i=0; $i<=count($matches[0]); $i++) { 
    for ($j=0; $j<=count($matches[0]); $j++) { 
    if (($var[$i][$j]) != '') { 
     print_r($var[$i][$j]); 
     echo '<br>'; 
    } 
    } 
} 
+0

您需要發佈UR查詢 –

+0

我的查詢是正確的,讓我用數字產品說明裏面 –

回答

0

如果你確信他們是4和6長之間:

$string = $sql['products_description']; 
preg_match_all('#\d{4,6}#', $string, $matches); 
foreach ($matches as $match) { 
    echo $match; 
} 

我只修改了模式和for循環。如果你想讓它 「純粹的」

編輯:

$string = $sql['products_description']; 
$var = array(); 
preg_match_all('#\d{4,6}#', $string, $matches); 
foreach ($matches as $match) { 
    $var[] = $match; 
} 
+0

關閉。我修改了這個,但仍然沒有工作。這一個打印像Array([0] => 1500 [1] => 30459 [2] => 30458),我想他們純粹,而不是在一個數組。 –

+0

你是否希望他們逗號分開,因爲我沒有完全理解「純粹」的含義。 – Kenny

+0

該版本僅返回單詞「Array」。我的意思是「純粹」像打印數字一個接一個或可以放入$ var。例如是$ var [$ I] = $匹配[$ i]於; - > $ var1 = 1234/$ var2 = 123456等...如果單獨打印,我也可以使用$ var。 –

1

試試這個代碼:

preg_match_all('!\d+!', $str, $matches); 
print_r($matches); 

編輯:

preg_match_all('/[456]/', $str, $matches); 
$var = implode('', $matches[0]); 
print_r($var) 
+0

沒有,我想從4〜6個號碼的匹配,並打印出來純粹(不在數組中) –

+0

你的版本返回5 4 5 4 5 - >這是什麼? –

+0

第二個正則表達式是完全錯誤的。 – Kenny

1
 preg_match_all('!\d+!', $str, $matches); 
    print_r($matches); 
    $digit=$matches[0][0]; 
    $digit=(int)$digit; 
    echo $digit; 

你會得到烏爾號這樣..

編輯#1


print_r($matches[0]); 
    //Output : 
     Array 
      (
      [0] => 1234, 
      [1] => 123456, 
      [2] => 1234 


      ) 
    echo implode("",$matches[0]); 
    //Output: 12341234561234 

編輯#2


$var1=$matches[0][0]; 
    $var2=$matches[0][1]; 
    $var3=$matches[0][2]; 
+0

$數字返回零。 –

+0

@KelsonB​​atista請重新檢查..我編輯了我的回答 –

+0

仍然無法正常工作,它只返回第一個數字,如1234 –

相關問題