How can I use a variable name in preg_grep?
I'm iterating over an array of file names and trying to match to the file name in the format of "Some File-0.png", "Some File-1.png" so on and so forth.
Here's what I'm using.
$arrayRet=preg_grep("/$filename-\\d*.png/",$ret);
I know the $ character is a special pattern character but I don't know how to escape it or if that's even the problem.
I've tried this but to no avail.
$pattern = "/".$filename."-\d*.png/";
$arrayRet=preg_grep($pattern,$ret);
EDIT: $ret returns a list of files such as this.
Array
(
[0] => C:\inetpub\wwwroot\Presentation\thumbs\...\Client References - Government-0.png
[1] => C:\inetpub\wwwroot\Presentation\thumbs\...\Client References - Government-1.png
[2] => C:\inetpub\wwwroot\Presentation\thumbs\...\Client References - National-0.png
[3] => C:\inetpub\wwwroot\Presentation\thumbs\...\Client References - National-1.png
[4] => C:\inetpub\wwwroot\Presentation\thumbs\...\Client References - National-2.png
[5] => C:\inetpub\wwwroot\Presentation\thumbs\...\Client References-0.png
[6] => C:\inetpub\wwwroot\Presentation\thumbs\...\Client References-1.png
[7] => C:\inetpub\wwwroot\Presentation\thumbs\...\Company Profile-0.png
[8] => C:\inetpub\wwwroot\Presentation\thumbs\...\Company Profile-1.png
[9] => C:\inetpub\wwwroot\Presentation\thumbs\...\Corporate Overview - Short Version-0.png
[10] => C:\inetpub\wwwroot\Presentation\thumbs\...\Corporate Overview - Short Version-1.png
Note - I've added ellipses to shorten the path.
$filename would be Client References - Government
, Client References - National
, Client References
and so on.
Use preg_quote
to escape all special regex meta characters:
$pattern = '/' . preg_quote($filename, '/') . '-\d*.png/';
$arrayRet = preg_grep($pattern, $ret);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.