[英]What's wrong with this php/regex query?
preg_replace("/(/s|^)(php|ajax|c\+\+|javascript|c#)(/s|$)/i", '$1#$2$3', $somevar);
例如,它打算将PHP变成#PHP。
Warning: preg_replace(): Unknown modifier '|'
It's because you are using the forward slash ( /
) as your delimiter. 这是因为您使用正斜杠(
/
)作为分隔符。 When the regex engine gets to /s
(3rd character) it thinks the regex is over and the rest of it are modifiers. 当正则表达式引擎到达
/s
(第三个字符)时,它认为正则表达式已结束,其余部分都是修饰符。 But no such modifier ( |
) exists, thus the error. 但是不存在这样的修饰符(
|
),因此会出现错误。
Next time, you can either: 下次,您可以:
Change your delimiters to something you won't use in your regex, ie: 将定界符更改为您将不在正则表达式中使用的内容,即:
preg_replace("!(/s|^)(php|ajax|c\\+\\+|javascript|c#)(/s|$)!i", '$1#$2$3', $somevar);
Or escape those characters with a backslash, ie: "/something\\/else/"
* 或用反斜杠转义那些字符,即:
"/something\\/else/"
*
I also suspect you didn't intend to use /s
, but the escape character \\s
that matches whitespace characters. 我也怀疑您不打算使用
/s
,而是使用与空格字符匹配的转义字符\\s
。
The first character in the regular expression is the delimiter. 正则表达式中的第一个字符是定界符。 If you need to use this inside your regular expression then you need to escape it:
如果您需要在正则表达式中使用此函数,则需要对其进行转义:
"/(\/s|^)...
^
Or alternatively, choose another delimiter that isn't used anywhere in your regular expression so that you don't need to escape: 或者,选择另一个不在正则表达式中使用的定界符,这样就无需转义:
"~(/s|^)...(/s|$)~i"
I prefer to do the latter as it makes the regular expression more readable. 我更喜欢后者,因为它使正则表达式更具可读性。
(Although as NullUserException points out, the actual error is that you should have used a backslash instead of a slash). (尽管正如NullUserException指出的那样,实际错误是您应该使用反斜杠而不是斜杠)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.