0

我不确定它的标题,但是有一个这样的正则表达式:

preg_replace('#static\/(.*)(\/|\.[a-zA-Z0-9]{2,4})#', 'path=$1$2');

它应该匹配static/path/to/image.jpgstatic/path/to/dir/。现在我想如果匹配第二个模式(一个目录)所以用前导斜杠替换它,但如果匹配到一个文件名(第一个模式)替换它没有前导斜杠。

例子:

`static/path/to/image.jpg` should be 'path=path/to/image.jpg'
`static/path/to/image.jpg/` should be 'path=path/to/image.jpg'
`static/path/to/dir/` should be 'path=path/to/dir/'

简而言之,$2如果等于/最后请求的文件,我想被忽略。以为添加?:可以解决问题,但我错了。

有没有办法做这样的事情?

4

2 回答 2

1

假设路径位于 URL 的末尾:

preg_replace('#static((?:/[^./]*(?=/))*)(/(?:\w+\.\w+)?)/?$#', 'path=$1$2');

或没有前瞻(更快):

preg_replace('#static(/(?:[^./]*/)*)(\w+\.\w+)?/?$#', 'path=$1$2');

编辑:修改了正则表达式,并添加了 OP 的说明

于 2013-01-28T08:12:26.977 回答
0

本质上,您只是替换static/path=(如果跟随路径名),对吗?

然后这样做:

$result = preg_replace(
    '%static/      # Match static/
    (?=            # only if the following text could be matched here:
     \S+           # one or more non-whitespace characters,
     (?:           # followed by
      /            # a slash
     |             # or
      \.\w{2,4}    # a filename extension
     )             # End of alternation.
     (?!\S)        # Make sure that there is no non-space character here
    )              # End of lookahead.%x', 
    'path=', $subject);
于 2013-01-28T08:03:00.263 回答