A package to easily work with regex in PHP
PHP offers some functions to work with regular expressions, most notably preg_match
, preg_match_all
and preg_replace
. Unfortunately those functions are a bit hard to use. Take preg_match_all
for example, it requires you to pass in an array by reference to get all the matches. When something goes wrong some of those preg_
functions return false
, while others return null
. To get to the actual error message some truly horrible stuff needs to be done.
To make working with regex a bit more developer-friendly my colleague Sebastian coded up a new package called regex. Here's how you can work with it:
use Spatie\Regex\Regex;
// Using `match`
Regex::match('/a/', 'abc'); // `MatchResult` object
Regex::match('/a/', 'abc')->hasMatch(); // true
Regex::match('/a/', 'abc')->result(); // 'a'
// Capturing groups with `match`
Regex::match('/a(b)/', 'abc')->result(); // 'ab'
Regex::match('/a(b)/', 'abc')->group(1); // 'a'
// Using `matchAll`
Regex::matchAll('/a/', 'abcabc')->hasMatch(); // true
Regex::matchAll('/a/', 'abcabc')->results(); // Array of `MatchResult` objects
// Using replace
Regex::replace('/a/', 'b', 'abc')->result(); // 'bbc';
Regex::replace('/a/', function (MatchResult $result) {
return $result->result() . 'Hello!';
}, 'abc')->result(); // 'aHello!bc';
I'm pretty sure you agree this is much easier to work with (if you're not a regex-expert, but more of an occasional regex user). Take a look at the full documentation on GitHub to learn all the options. This isn't the first package our team has made, head over to our company website to view a list of all previously released packages.
You can use Bog Jug for easy work with regex groups.