Properly formating preg_match()

why is preg_match skipping a file and adding one at the end?

here is the code:

<?php 
$files = array_diff( scandir("images/associates"), array(".", "..","_notes") );
	
	foreach($files as $file){
		echo $file,'<br />';
 
if (preg_match('/^692_/', $file)){
	echo 'match found  ';
	}
	else{echo 'no match found  ';}
}
?>

and the result looks like this:

679_bjaad.jpg
no match found 692_Image1.jpg
match found 692_alsuitsmblur.jpg
match found 692_bjaad.jpg
match found 694_alsuitsmblur.jpg
no match found 694_blury.jpg
no match found 694_dec08.jpg
no match found 694_dec1408.jpg
no match found 694_jsuit.jpg
no match found 694_teyejaad.jpg
no match found 710_alsuitsmblur.jpg
no match found 712_bjaad.jpg
no match found

ok I think I know what it is… am I right by saying preg_match echo the file name first and then the echoed match found or not found after? inserting a break simply shift things one line?

Yes, the way that code is written the “match”, “no match” is about the $file above it.

Maybe this would be better for you?


	foreach($files as $file){
		echo $file;  
if (preg_match('/^692_/', $file)){
	echo 'match found  ';
	}
	else{echo 'no match found  ';}
      echo '<br />';
}

yes it does, thank you very much…

So now that this test is working for me, would you know if I can use a code inside a string with preg_ match?

ex:
if(!empty($pic)) {
$files = array_diff( scandir(“images/associates”), array(“.”, “…”) );
foreach($files as $file){
if (preg_match('/^$user->data()->id . “"/', $file)){ --------------Where ->$user->data()->id . "” is user id followed by_ filename
echo ‘You already have a picture on file ->’.$file;
}else
{go ahead and process the rest of the script…}
}

If user ids are the 692, 694 710 and 712 in your example, I would do something like this

$pattern = "/^" . $user->data()->id . "_/"; 
.....
if (preg_match($pattern, $file))

untested, so do a
var_dump($pattern)
to make sure it looks right.

preg_match("'/^". $user->data()->id . "_". "/'", $file))

I tried a few variation from your idea, this one above worked. thanks a bunch

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.