是否有一个函数可以转义正则表达式字符串中的特殊字符?

发布于 2024-12-10 19:04:34 字数 395 浏览 0 评论 0原文

我试图匹配某些文本中的某些链接:

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

葮薆情 2024-12-17 19:04:34

你有很多语法错误。您必须转义所有特殊字符,如“.”、“?”等等。因此,您必须像这样替换字符:

'.' -> '\.'
'?' -> '\?'
...

无论如何,正则表达式应该是这样的:

$reg = '#ok is it http:\/\/google\.com/\?s=us#';

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:

$reg = '#ok is it http:\/\/google\.com/\?s=us#';
隔岸观火 2024-12-17 19:04:34

某些字符被 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 \\\\.

长发绾君心 2024-12-17 19:04:34

使用:

$reg = '#ok is it http://google.com/\?s=us#';

Use:

$reg = '#ok is it http://google.com/\?s=us#';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文