我试图添加评论以使正则表达式更清晰
// Strip any URLs (such as embeds) taken from http://stackoverflow.com/questions/6427530/regular-expression-pattern-to-match-url-with-or-without-http-www
$pattern =
'( # First capturing group
(http|https) # Second capturing grout,matches wither http or https
\:\/\/)? # End of first capturing group, matches :// exactly
[ # Match any char in the following list. the + after the closing bracke means greedy
a-z # Any char between a and z
A-Z # Any char between A and Z
0-9 # Any char between 0 and 9
\.\/\?\:@\- # ./?:@- literally ( any one of them )
_=# # _=# any of these thre chars
]+ # end of list
\. # matches .
( # third caturing group
[ # start of list
a-z # Any char between a and z
A-Z # Any char between A and Z
0-9 # Any char between 0 and 9
\.\/\?\:@\- # ./?:@- literally ( any one of them )
_=# # _=# any of these thre chars
] # end of list
)* # end of capturing group with greedy modifier';
$excerpt = preg_replace("/$pattern/x", '', $excerpt );
但我收到了警告
警告:preg_replace():未知的修饰符' /'在第280行
我该如何评论?
答案 0 :(得分:5)
这可能不是最干净的方法,但您可以将每个部分括在引号中并将它们连接起来。
这样的事情应该有效:
$pattern =
'('. // First capturing group
'(http|https)'. // Second capturing grout,matches wither http or https
'\:\/\/)?'. // End of first capturing group, matches :// exactly
...
或者我在PHP文档中找到了this。
所以我想这也会奏效,但你使用的是x
修饰符,而且它应该已经有效了。
如果设置了PCRE_EXTENDED选项,则字符类外部的未转义#字符会引入注释,该注释将一直延续到模式中的下一个换行符。
这表示字符集[...]
中的所有评论均无效。
以下是与PCRE_EXTENDED
修饰符一起使用的工作示例:
$pattern = '
( # First capturing group
(http[s]?) # Second capturing grout,matches wither http or https
\:\/\/)? # End of first capturing group, matches :// exactly
[a-zA-Z0-9\.\/\?\:@\-_=#]+ # [List Comment Here]
\. # matches .
( # third caturing group
[a-zA-Z0-9\.\/\?\:@\-_=#] # [List Comment Here]
)* # end of capturing group with greedy modifier
';
答案 1 :(得分:4)
这是in a comment on the php.net modifiers page。
引用:
使用/ x修饰符添加注释时,请勿在注释中使用模式分隔符。在评论区域中可能不会忽略它。
在您的示例中,您的一条评论中嵌入了字符串://
。由于PHP似乎没有通过考虑标志来解析正则表达式分隔符,因此它将此视为一个问题。使用以下代码可以看到相同的内容:
echo preg_replace('/
a #Com/ment
/x', 'e', 'and');
您需要更改分隔符或转义注释中的分隔符。