PHP Regex Lookahead/Lookbehind 🎯

beginner
10 min

PHP Regex Lookahead/Lookbehind 🎯

Welcome to another exciting lesson at CodeYourCraft! Today, we're going to dive into the fascinating world of PHP Regular Expressions (regex) and explore Lookahead and Lookbehind, powerful tools to refine your pattern matching skills.

Regular expressions are a powerful tool in PHP that allows you to search, replace, and manipulate text according to a specified pattern. Lookahead and Lookbehind are advanced regex features that let you check a certain condition in your pattern without actually consuming the characters.

What are Lookahead and Lookbehind? πŸ“

Lookahead and Lookbehind are positive and negative assertions in regex that help you match patterns based on specific conditions in the text.

  • Lookahead (?=...) checks if a specific pattern appears after the current position.
  • Lookbehind (?<=...) checks if a specific pattern appears before the current position.

Basic Syntax πŸ’‘

(?=pattern) # Positive Lookahead (?<=pattern) # Negative Lookbehind

Let's dive into some practical examples to understand these better.

Example 1: Positive Lookahead βœ…

Let's say we have a simple string:

$text = "I like blue, red, and green colors.";

And we want to find all the colors that come after "like". Here's how we can use Positive Lookahead:

$pattern = '/\blike\s+(?=\bcolor\b)/'; preg_match_all($pattern, $text, $matches); print_r($matches[0]);

This code will output array(2) { [0] => "blue" [1] => "red" }, as it finds all words that come after "like" and are followed by "color".

Example 2: Negative Lookbehind βœ…

Let's say we have a more complex string:

$text = "I don't like 123, 456, and 789 numbers.";

And we want to find all the numbers that are not preceded by a dash. Here's how we can use Negative Lookbehind:

$pattern = '/\b(?<!-)\d+/'; preg_match_all($pattern, $text, $matches); print_r($matches[0]);

This code will output array(3) { [0] => "789" }, as it finds all words that are numbers and not preceded by a dash.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What is the output of the following code?

Remember, regex Lookahead and Lookbehind are advanced techniques that can make your pattern matching more precise. With practice, they'll become indispensable tools in your PHP programming arsenal.

Stay tuned for more exciting lessons here at CodeYourCraft! πŸš€