【问题标题】:Trying to convert rewriterule regex into php regex with minimal regex modification尝试以最少的正则表达式修改将 rewriterule 正则表达式转换为 php 正则表达式
【发布时间】:2015-11-21 22:59:24
【问题描述】:

我的 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

正则表达式被正确处理并将url转发到“whatever”。

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

<?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 配置文件中编写的正则表达式。我该如何解决?还是有可能?

【问题讨论】:

  • 转义特殊字符。比如正则表达式本身的分隔符
  • 您可能想要更改分隔符,php.net/manual/en/regexp.reference.delimiters.php
  • 更改分隔符对我来说部分有用,但它并没有吸收所有元素,特别是 (image|thumbnail|page) 部分......现在没关系......我想我让它工作是因为分隔符更改。我必须使两个字符串的大小写测试和正则表达式相同。
  • preg_match _all()

标签: php regex apache .htaccess mod-rewrite


【解决方案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

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多