Home  >  Article  >  Backend Development  >  How to escape dots in php regular expressions

How to escape dots in php regular expressions

PHPz
PHPzOriginal
2023-03-29 10:13:36662browse

In PHP, using regular expressions to match specific strings is an important skill. In regular expressions, the period (.) matches any character. However, sometimes we need to match real periods, not any characters. In this case, we need to use an escape character to escape the period.

The escape character is to add a backslash () before a special character. In PHP, the backslash is used as an escape character to recognize the following characters:

  • \' Single quote
  • \" Double quote
  • \ Back Slash
  • \n Line feed character
  • \r Carriage return character
  • \t Tab character
  • \f Form feed character
  • \v vertical tab character

In regular expressions, the dot (.) is a special character, so it also needs to be escaped with a backslash. If you do not escape the dot , it will be treated as any character and match any character in the input string.

Here is an example of using escape characters to match dots:

// 匹配真正的点号
$string = 'Hello world.';

// 匹配一个字符串,它以一个字母开头,后跟一个点号,并且后面还有其他字符
$pattern = '/^[a-z]\.+.+/i';

if (preg_match($pattern, $string)) {
    echo "匹配成功!";
} else {
    echo "匹配失败!";
}

In the above example , we use the regular expression /^[a-z]\. . /i to match a string that starts with a letter, is followed by a period, and is followed by other characters. In the regular expression , the dot is escaped with a backslash to match a real dot.

To summarize, it is very simple to use regular expressions to escape dots in PHP. Just add a backslash before the dot A dash will do. Doing this ensures that you are matching a real period and not accidentally matching any characters in the regular expression.

The above is the detailed content of How to escape dots in php regular expressions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn