...

/

Regular Expression Syntax Primer

Regular Expression Syntax Primer

Learn the basic syntax of regular expressions using method signatures.

Regular expressions are one of those topics that often feel obscure, intimidating, or too difficult to grasp; most of these descriptions can largely be attributed to the difficulty in reading nontrivial regular expressions. However, despite this, they are a straightforward yet powerful way to express search patterns that can be applied to text. Throughout this course, we have used several regular expressions to help us achieve our goals in one way or another. For example, we have used regular expressions often to quickly scan text input to locate all instances of a particular pattern and to remove substrings, amongst other things. However, we have not taken time to step back and explore regular expressions themselves.

To begin our discussion around regular expressions, let’s consider the example below:

Press + to interact
<?php
$url = 'blog/2022-10-12/title';
if (preg_match('/^blog\/.*\z/u', $url) === 1) {
// The URL starts with "blog/"
} else {
// The URL does not start with "blog/"
}

In the code above, we are using a simple regular expression to determine if the input string begins with blog/. The amount of boilerplate code we have used to perform this comparison can be reduced by using one of Laravel’s string helper methods: the is helper method.

Press + to interact
<?php
/**
* Versions Laravel 8, 9
*
* @return bool
*/
public static function is(
string|array $pattern,
string $value
);

We can rewrite our sample from first code using the is helper method like so:

Press + to interact
<?php
use Illuminate\Support\Str;
if (Str::is('blog/*', $url)) {
// The URL starts with "blog/"
} else {
// The URL does not start with "blog/"
}

When we compare the logic between both approaches, it is much easier to quickly scan the second code and understand the intention behind the condition. An ...