是否有一个函数可以转义正则表达式字符串中的特殊字符?
我试图匹配某些文本中的某些链接:
$reg = '#ok is it http://google.com/?s=us#';
$page = 'Well i think ! ok is it http://google.com/?s=us&ui=pl0 anyways it ok';
if (preg_match($reg,$page)) {
echo 'it work';
} else {
echo 'not work';
}
如果我使用 $reg = '#ok is it http://google.com/';
那么就可以了,但是当我使用该模式时“?=”不匹配。
我知道存在语法错误的问题。是否有任何函数或现成的函数可以自动转义这些特殊字符?
I am trying to match some link from some texts:
$reg = '#ok is it http://google.com/?s=us#';
$page = 'Well i think ! ok is it http://google.com/?s=us&ui=pl0 anyways it ok';
if (preg_match($reg,$page)) {
echo 'it work';
} else {
echo 'not work';
}
If I use $reg = '#ok is it http://google.com/';
then it's okay, but when I use that pattern with "?=" it doesn't match.
I understand there is some problem of a syntax error. Is there any function or ready made function which automatically escape these special characters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你有很多语法错误。您必须转义所有特殊字符,如“.”、“?”等等。因此,您必须像这样替换字符:
无论如何,正则表达式应该是这样的:
You have a lot of syntax errors. You must escape all the special chars as '.', '?' and so on. Thus you have to replace the chars like this:
Anyway, the regex should be like this:
某些字符被 REGEX 引擎读取为元字符,这意味着它们在引擎的程序中具有特殊功能,例如 ? (问号),\(斜杠),. (句点)、*(星号)等等。
正如使用包含元字符的 SQL 发送的字符串一样,您需要通过添加尾部斜杠来手动转义这些字符: \. 当转义 \ 字符时,您可能需要将其转义三个或像这样四次:\\\或\\\\。
Some characters are read as metacharacters by the REGEX engine, meaning that they have a special function within the engine's procedures, a few examples being ? (question mark), \ (slash), . (period), * (asterisk) etcetera.
Just as with strings you would send with SQL that contains metacharacters, you will need to escape these characters manually by adding a trailing slash: \. When escaping the \ character, you might need to escape it three or four times like this: \\\ or \\\\.
使用:
Use: