Preg_match still driving me nuts

Now on day 3 with a gazillion variations I do not get it to work. I have reduced the code to the bare minimum, checked the regex against Rubular (it works there) - still in the code preg_match stubbornly returns zero although it is obvious that 6 digits should find a match in $test:

 <?php


$regex = '/^[0-9]{6}$/';
$test = "28 888469 29 571086 dfghjytr 30 888192 31 570472 32 888470 33 888471";

$pos = preg_match($regex, $test, $matches, PREG_OFFSET_CAPTURE);
 	if (!$pos === 0){
 		
 		echo "<br>";
 		print_r($matches);

	}else{
		echo "not in $test";
		
	}

 echo "<br>";
 echo 'end program';
?>

^...$ means starting at the first character and finishing at the last. But the string you are searching for is within, there could be non-matching characters at start and end. Also !$pos === 0 would invert $pos first, then compare that with zero.

<?php


$regex = '/[0-9]{6}/';
$test = "28 888469 29 571086 dfghjytr 30 888192 31 570472 32 888470 33 888471";

$pos = preg_match($regex, $test, $matches, PREG_OFFSET_CAPTURE);
var_dump($pos);
var_dump($matches);
 	if ($pos !== 0){
 		
 		echo "<br>";
 		print_r($matches);

	}else{
		echo "not in $test";
		
	}

 echo "<br>";
 echo 'end program';
?>
1 Like

OK a combination of your

$regex = '/[0-9]{6}/';

and

if ($pos == 1){

finally worked!

thank you!

I somehow expected the resulting array to contain all occurences of a match, however it only finds the first one. what am I missing?

Array ( [0] => Array ( [0] => 888469 [1] => 3 ) )

Use preg_match_all()

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service