【问题标题】::conditional RegEx to ingore a value:conditional RegEx 忽略一个值
【发布时间】:2013-01-28 07:22:06
【问题描述】:

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

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。以为添加 ?: 可以解决问题,但我错了。

有没有办法做到这一点?

【问题讨论】:

  • 我觉得你的问题很难理解。你能提供前后的例子吗?
  • 您的示例与您的描述不符。你的意思是'path=path/to/dir' without slash
  • 我说 Now i want if matched the 2nd pattern (a directory) so replace it with leading slash 和例子是一样的,我的意思是 'path=path/to/dir/' 带有斜线
  • 你也说过In simple words, I want $2 to be ignored if equals to /. 那不是同一个意思。已发布适合第一个描述的答案。
  • @robinCTS 你是对的,问题有点令人困惑。现在我用更好的描述和示例进行了编辑。

标签: php regex preg-replace


【解决方案1】:

假设路径在 URL 的末尾:

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

或没有前瞻(更快):

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

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

【讨论】:

  • 我正在重写 URL,所以像 static/images.png/ 这样的东西将被替换为 path=image.png/ 并带有前导斜杠
  • @Omid - 您能否在您的问题中添加一个 complete URL 示例以及您想要的结果。这样我就可以确定正则表达式会起作用。
  • 添加了另一个示例,如果您想了解更多信息,lemmi 知道
  • @Omid - 我想我知道你的意思。除非您所在的路径位于 URL 的中间,否则答案将起作用。不确定 PHP 如何在更快的正则表达式中处理未捕获的捕获组。在发布之前必须在线测试。
  • 你做到了,谢谢,我们可以联系吗?
【解决方案2】:

本质上,您只是将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);

【讨论】:

  • 为什么你认为应该有one or more non-whitespace characters
  • @Omid:您的路径名中是否允许使用未编码的空格?它们不应该是,因此\S. 更具体,如果您的字符串可能包含多个路径,则它变得相关。您的问题没有说明这一点。
猜你喜欢
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多