在PHP中使用preg_grep匹配中的变量

时间:2015-02-18 17:18:23

标签: php regex

如何在preg_grep中使用变量名?

我遍历文件名数组并尝试以" Some File-0.png"," Some File-1的格式匹配文件名。 PNG"等等。

这是我正在使用的内容。

$arrayRet=preg_grep("/$filename-\d*.png/",$ret);

我知道$ character是一个特殊的模式角色,但我不知道如何逃脱它,或者甚至是问题。

我试过这个但是没有用。

$pattern = "/".$filename."-\d*.png/";
$arrayRet=preg_grep($pattern,$ret);

编辑:$ 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将为Client References - GovernmentClient References - NationalClient References等等。

1 个答案:

答案 0 :(得分:2)

使用preg_quote来转义所有特殊的正则表达式元字符:

$pattern = '/' . preg_quote($filename, '/') . '-\d*.png/';
$arrayRet = preg_grep($pattern, $ret);