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 get last matched occurrence in PHP regex?
- How to use PHP regex to match a zip code?
- How to convert a PHP regex to JavaScript regex?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match special characters?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match an XML tag?
- How to get the first match when using regex in PHP?
- How to use PHP regex to match a year?
- How to match a space using PHP regex?
See more codes...