转义字符串用于正则表达式 [英] Escaping string for use in regular expression

查看:239
本文介绍了转义字符串用于正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

是否有PHP函数可以在应用前转义正则表达式模式?

我想使用正则表达式中存储在变量中的字符串。在(PCRE)正则表达式中避免使用字符串的最佳方式是什么(PHP)?

I want to use a string stored in a variable in a regular expression. What's the best way (in PHP) to escape a string for use in a (PCRE) regular expression?

例如,

$text = 'm/z';  // this is the text I want to use as part of my regular expression
$text_regexp = '#' . $text . '#i';  // this is my regular expression

会给

$text_regexp = '#m/z#i';

但是我想要以下正则表达式:

But I would want the following regular expression:

$text_regexp = '#m\/z#i';

这是一个有创意的例子,但我想简单的说明一下。

This is a contrived example, but I wanted to illustrate the point simply.

推荐答案

preg_quote

从手册中


在每个$ b前面放置一个反斜杠$ b字符是常规
表达式语法的一部分

puts a backslash in front of every character that is part of the regular expression syntax

您还可以将分隔符作为第二个参数传递也将逃脱。但是,如果您使用作为分隔符,则不需要转义 /

You can also pass the delimiter as the second parameter and it will also be escaped. However, if you're using # as your delimiter, then there's no need to escape /

这篇关于转义字符串用于正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆