在PHP中的preg_grep匹配中使用变量
如何在preg_grep中使用变量名 我正在迭代一个文件名数组,并尝试以“Some file-0.png”、“Some file-1.png”等格式匹配文件名 这是我用的在PHP中的preg_grep匹配中使用变量,php,regex,Php,Regex,如何在preg_grep中使用变量名 我正在迭代一个文件名数组,并尝试以“Some file-0.png”、“Some file-1.png”等格式匹配文件名 这是我用的 $arrayRet=preg\u grep(“/$filename-\d*.png/”,$ret) 我知道$character是一个特殊的模式字符,但我不知道如何避开它,或者这是否是问题所在 我试过了,但没用 $pattern = "/".$filename."-\d*.png/"; $arrayRet=preg_grep($
$arrayRet=preg\u grep(“/$filename-\d*.png/”,$ret)代码>
我知道$character是一个特殊的模式字符,但我不知道如何避开它,或者这是否是问题所在
我试过了,但没用
$pattern = "/".$filename."-\d*.png/";
$arrayRet=preg_grep($pattern,$ret);
EDIT:$ret返回这样的文件列表
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
注意-我添加了省略号以缩短路径
$filename将是客户引用-政府
,客户引用-国家
,客户引用
,等等。使用preg_quote
转义所有特殊的正则表达式元字符:
$pattern = '/' . preg_quote($filename, '/') . '-\d*.png/';
$arrayRet = preg_grep($pattern, $ret);
“$filename”
插入变量内容,$
不会成为锚点。示例文件名不需要转义,但是锚定regex^
$
可能是合理的,或者覆盖大小写敏感度。在这种情况下,fnmatch()
和循环/数组过滤器回调可能是一种替代方法。同时启用错误报告
并详细说明“无效”部分。@mario谢谢。我尝试用$arrayRet=preg\u grep(“/^$filename-\d*.png/”,$ret)锚定正则表达式代码>并且没有任何更改。我还启用了error\u reporting
,正则表达式仍然返回一个没有错误的空数组。那么,它与任何内容都不匹配。只有你能说出原因,因为你没有透露你的$ret
数组实际包含的内容。@mario好的,我已经为循环的每次迭代添加了$ret的内容和$filename的值。