4

我想从文本中搜索一个数字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)

我纯粹需要它们(而不是在数组中),因为我以后必须单独使用每个数字。在这种情况下,如何提取每个元素并打印出来?

解决方案:

$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>';
    }
  }
}
4

3 回答 3

1

试试这个代码:

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

编辑:

preg_match_all('/[456]/', $str, $matches);
$var = implode('', $matches[0]);
print_r($var)
于 2012-12-24T08:59:05.400 回答
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];
于 2012-12-24T09:13:43.897 回答
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;
}
于 2012-12-24T09:06:23.193 回答