9951 explained code solutions for 126 technologies


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 contains Hello followed by a whitespace and World.
  • 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

Edit this code on GitHub