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 に答える