I want to search for a number in text from DB
and print them. Numbers are product codes and vary from 4 to 6 digits.
Example:
aaaaa 1234 aaaa
aaaaa 123456 aaaaa
aaaaa 12345 aaaaa
What I got is an array with exact match of 5 numbers, but not varying and not printing:
$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>';
}
Any help?
edit: I got this working closely:
$string = $sql['products_description'];
preg_match_all('#\d{4,6}#', $string, $matches);
foreach ($matches as $match) {
print_r($match);
}
but returns something like:
Array ( [0] => 1234 [1] => 123456 [2] => 12345 )
I need them purely (not in an array) because I have to use each number separately later. In this case, how to extract each element and print it?
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>';
}
}
}
If you are sure that they are between 4 and 6 long:
$string = $sql['products_description'];
preg_match_all('#\d{4,6}#', $string, $matches);
foreach ($matches as $match) {
echo $match;
}
I only modified the pattern and the for-loop.
Edit if you want it "purely":
$string = $sql['products_description'];
$var = array();
preg_match_all('#\d{4,6}#', $string, $matches);
foreach ($matches as $match) {
$var[] = $match;
}
Try this code:
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
Edit:
preg_match_all('/[456]/', $str, $matches);
$var = implode('', $matches[0]);
print_r($var)
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
$digit=$matches[0][0];
$digit=(int)$digit;
echo $digit;
You will get ur number this way..
Edit#1
print_r($matches[0]);
//Output :
Array
(
[0] => 1234,
[1] => 123456,
[2] => 1234
)
echo implode("",$matches[0]);
//Output: 12341234561234
Edit#2
$var1=$matches[0][0];
$var2=$matches[0][1];
$var3=$matches[0][2];