php-regexHow to use backslash in PHP regex?
Using backslash in PHP regex is a way to escape special characters. For example, if you want to match a literal dot character, you need to escape it with a backslash.
$string = 'This is a string with a dot.';
$pattern = '/\./';
if (preg_match($pattern, $string)) {
echo 'Match found!';
}
Output example
Match found!
Code explanation
$string = 'This is a string with a dot.';
- This is the string we are searching in.$pattern = '/\./';
- This is the pattern we are searching for. The backslash is used to escape the dot character, so that it is treated as a literal character instead of a special character.if (preg_match($pattern, $string)) {
- This is the function that is used to search for the pattern in the string.echo 'Match found!';
- This is the output that is printed if a match is found.
Helpful links
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to match a space using PHP regex?
- How to use PHP regex to match a zip code?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match an exact string?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match URL path?
- How to use named capture groups in PHP regex?
- How to use PHP regex to match special characters?
See more codes...