php-regexHow to use PHP regex lookahead?
PHP regex lookahead is a powerful tool for pattern matching. It allows you to look ahead in a string and check for a certain pattern without actually consuming the characters.
Example code
$string = 'Hello World';
$pattern = '/Hello(?=\sWorld)/';
if (preg_match($pattern, $string)) {
echo 'Match found!';
}
Output example
Match found!
Code explanation
$string = 'Hello World';- This is the string we are searching in.$pattern = '/Hello(?=\sWorld)/';- This is the pattern we are searching for. The(?=\sWorld)part is the lookahead assertion. It checks if the string containsHellofollowed by a whitespace andWorld.preg_match($pattern, $string)- This function searches for the pattern in the string.echo 'Match found!';- This line is executed if the pattern is found.
Helpful links
More of Php Regex
- How to match a single quote in PHP regex?
- How to use PHP regex to match a zip code?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match an exact string?
- How to use the "s" modifier in PHP regex?
- How to match a double quote in PHP regex?
- How to use PHP regex with the "x" modifier?
- How to replace strings using PHP regex?
- How to match a quotation mark in PHP regex?
See more codes...