尝试将rewriterule正则表达式转换为php正则表达式,只需最少的正则表达式修改

时间:2015-11-21 22:59:24

标签: php regex apache .htaccess mod-rewrite

我的httpd.conf中有以下内容:

RewriteRule ^galleries/?([0-9]{4})?([0-9]{2})?([0-9]{2})?([a-z0-9_-]+)?/?(image|thumbnail|page)?s?/?([A-Z]+)?([0-9]+)?\.?(.+)?$ whatever [NC,L]

当有人访问以下任何一个时:

http://example.com/galleries/20140630ABC/image/x1.jpg
http://example.com/galleries/20140520DEF/image/x22.jpg

正确处理正则表达式并将网址转发给“无论什么”。

然后我尝试用最少的修改创建我的正则表达式的PHP版本。这是我第一次尝试在代码的第二行使用测试字符串:

<?php
$is="galleries/20140630ABC/image/x1.jpg";
$p='^galleries/?([0-9]{4})?([0-9]{2})?([0-9]{2})?([a-z0-9_-]+)?/?(image|thumbnail|page)?s?/?([A-Z]+)?([0-9]+)?\.?(.+)?$';
echo preg_match($p,$is,$mat);
print_r($mat);
?>

上面的代码产生了这个错误:

Warning: preg_match(): No ending delimiter '^' found in /path/to/code.php on line 4

然后我用引号内的斜线包围了我的正则表达式。我的代码是这样的:

    <?php
    $is="galleries/20140630ABC/image/x1.jpg";
    $p='/^galleries/?([0-9]{4})?([0-9]{2})?([0-9]{2})?([a-z0-9_-]+)?/?(image|thumbnail|page)?s?/?([A-Z]+)?([0-9]+)?\.?(.+)?$/';
    echo preg_match($p,$is,$mat);
    print_r($mat);
    ?>

我收到了这个错误:

Warning: preg_match(): Unknown modifier '?' in /path/to/code.php on line 4

我可能正在使用错误的函数,但是我想在PHP中评估它时,尽可能少地修改我在apache配置文件中编写的正则表达式。我该如何解决?或者甚至可能吗?

1 个答案:

答案 0 :(得分:1)

\转义/,它应该会更好。试试这个:

$re = "/^galleries\\/?([0-9]{4})?([0-9]{2})?([0-9]{2})?([a-z0-9_-]+)?\\/?(image|thumbnail|page)?s?\\/?([A-Z]+)?([0-9]+)?\\.?(.+)?$/"; 
$str = "galleries/20140630ABC/image/x1.jpg"; 

preg_match($re, $str, $matches);
print_r($str);

在此处查看:https://regex101.com/r/vV2vC5/1