How to escape php regular expression characters-PHP problem

In php, you can use the "preg_last_error" function to escape regular expression characters. The syntax is "stringpreg_quote(string$str[,string$delimiterNULL])".

In php, you can use the "preg_last_error" function to escape regular expression characters. The syntax is "string preg_quote (string $str [, string $delimiter = NULL] )".

 

Recommendation: "PHP Video Tutorial"

The preg_last_error function is used to escape regular expression characters.

grammar

1

string preg_quote ( string $str [, string $delimiter = NULL ] )

preg_quote() requires the parameter str and adds a backslash before each character in the regular expression syntax. This is usually used when you have some runtime strings that need to be matched as regular expressions.

The special characters of regular expressions are:. \ + *? [^] $ () {} =! <> |:-

Parameter Description:

$str: Input string.

$delimiter: If the optional parameter delimiter is specified, it will also be escaped. This is usually used to escape the separator used by the PCRE function. / Is the most common separator.

return value

Returns the escaped string.

Instance

Example 1

1

2

3

4

5

<!--?php

$keywords = '$40 for a g3/400';

$keywords = preg_quote($keywords, '/');

echo $keywords;

?-->

The execution result escapes the $ and / special characters, as shown below:

Return\$40 for a g3\/400

Replace words in text with italics

1

2

3

4

5

6

7

8

9

10

<!--?php

//在这个例子中,preg_quote($word) 用于保持星号原文涵义,使其不使用正则表达式中的特殊语义。

  

$textbody = "This book is *very* difficult to find.";

$word = "*very*";

$textbody = preg_replace ("/" . preg_quote($word) . "/",

                          "<i-->" . $word . "",

                          $textbody);

echo $textbody;

?>

The execution result is as follows:

1

This book is <i>*very*</i> difficult to find.

Guess you like

Origin blog.csdn.net/kexin178/article/details/112798423