2012-12-24 81 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 –

相关问题