【发布时间】:2013-01-28 07:22:06
【问题描述】:
我不确定它的标题,但是有一个这样的正则表达式:
preg_replace('#static\/(.*)(\/|\.[a-zA-Z0-9]{2,4})#', 'path=$1$2');
它应该匹配static/path/to/image.jpg 和static/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