YouTip LogoYouTip

Php Preg_Quote

## PHP preg_quote() Function The `preg_quote()` function is a built-in PHP function used to escape regular expression characters. It adds a backslash (`\`) before every character that has a special meaning in regular expression syntax. This function is highly useful when you have a dynamic, runtime string (such as user input) that you need to inject into a regular expression pattern without its special characters being interpreted as regex operators. --- ### Syntax ```php string preg_quote ( string $str [, string $delimiter = null ] ) ``` ### Parameters * **`$str`**: The input string containing the characters you want to escape. * **`$delimiter`**: *Optional.* If specified, the character provided in this parameter will also be escaped. This is typically used to escape the delimiter required by PCRE functions (most commonly the forward slash `/`). ### Special Characters Escaped by `preg_quote()` The function automatically detects and escapes the following regular expression special characters: `.` `\` `+` `*` `?` `[` `^` `]` `$` `(` `)` `{` `}` `=` `!` `<` `>` `|` `:` `-` > **Note:** The hash symbol `#` is not in the standard list of escaped characters. If you use `#` as your regex delimiter, you should pass it as the second argument (`$delimiter`) to ensure it gets escaped properly. ### Return Value Returns the escaped string. --- ### Code Examples #### Example 1: Basic Escaping with Delimiter In this example, we escape a string containing a price and a path-like structure. We also pass the forward slash `/` as the second argument so that it is safely escaped as well. ```php ``` **Output:** ```text \$40 for a g3\/400 ``` --- #### Example 2: Replacing Text Containing Special Characters In this example, `preg_quote()` is used to escape asterisks (`*`) in the search term. This ensures the asterisks are treated as literal characters rather than regex quantifiers. ```php " . $word . "", $textbody); echo $textbody; ?> ``` **Output:** ```text This book is *very* difficult to find. ``` --- ### Key Considerations 1. **Security & User Input:** Always use `preg_quote()` when building regular expressions dynamically from user input (e.g., search queries). Failing to do so can lead to unexpected regex compilation errors or potential Regular Expression Denial of Service (ReDoS) vulnerabilities. 2. **Choosing the Right Delimiter:** Always pass your regex delimiter (usually `/` or `#`) as the second argument to `preg_quote()`. If you omit it, the delimiter character within the string will remain unescaped, which will cause a syntax error when the regex engine parses the pattern.
← Php Preg_SplitPhp Preg_Grep β†’