Description
Php's built in preg_* functions require some odd patterns like passing variables by reference and treating false or null values as errors. spatie/regex provides a cleaner interface for preg_match, preg_match_all, preg_replace and preg_replace_callback.
Regex alternatives and similar libraries
Based on the "Strings" category.
Alternatively, view Regex alternatives based on common mentions on social networks and blogs.
-
Mobile-Detect
Mobile_Detect is a lightweight PHP class for detecting mobile devices (including tablets). It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment. -
SQL Formatter
A lightweight php class for formatting sql statements. Handles automatic indentation and syntax highlighting. -
Device Detector
The Universal Device Detection library will parse any User Agent and detect the browser, operating system, device used (desktop, tablet, mobile, tv, cars, console, etc.), brand and model. -
Slugify
Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte. -
Jieba-PHP
"結巴"中文分詞:做最好的 PHP 中文分詞、中文斷詞組件。 / "Jieba" (Chinese for "to stutter") Chinese text segmentation: built to be the best PHP Chinese word segmentation module. -
URLify
A fast PHP slug generator and transliteration library that converts non-ascii characters for use in URLs. -
Google Translate For Free
Library for free use Google Translator. With attempts connecting on failure and array support. -
Case converter
Convert strings between 13 naming conventions: Snake case, Camel case, Kebab case, Pascal case, Ada case, Train case, Cobol case, Macro case, Upper case, Lower case, Title case, Sentence case and Dot notation. -
Russian metaphone phonetic algorithm implementation for PHP
Russian metaphone algorithm implementation
InfluxDB - Power Real-Time Data Analytics at Scale
* Code Quality Rankings and insights are calculated and provided by Lumnify.
They vary from L1 to L5 with "L5" being the highest.
Do you think we are missing an alternative of Regex or a related project?
Popular Comparisons
README
Making regex great again
Php's built in preg_*
functions require some odd patterns like passing variables by reference and treating false
or null
values as errors. spatie/regex
provides a cleaner interface for preg_match
, preg_match_all
, preg_replace
and preg_replace_callback
.
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); // 'b'
// Setting defaults
Regex::match('/a(b)/', 'xyz')->resultOr('default'); // 'default'
Regex::match('/a(b)/', 'xyz')->groupOr(1, 'default'); // 'default'
// 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';
Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.
Support us
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
Installation
You can install the package via composer:
composer require spatie/regex
Usage
Matching a pattern once
Matches a pattern on a subject. Returns a MatchResult
object for the first match.
/**
* @param string $pattern
* @param string $subject
*
* @return \Spatie\Regex\MatchResult
*/
Regex::match(string $pattern, string $subject): MatchResult
MatchResult::hasMatch(): bool
Checks if the pattern matches the subject.
Regex::match('/abc/', 'abc')->hasMatch(); // true
Regex::match('/def/', 'abc')->hasMatch(); // false
MatchResult::result(): string
Return the full match that was made. Returns null
if no match was made.
Regex::match('/abc/', 'abc')->result(); // 'abc'
Regex::match('/def/', 'abc')->result(); // null
MatchResult::group(int $id): string
Return the contents of a captured group (with a 1-based index). Throws a RegexFailed
exception if the group doesn't exist.
Regex::match('/a(b)c/', 'abc')->group(1); // 'b'
Regex::match('/a(b)c/', 'abc')->group(2); // `RegexFailed` exception
Matching all occurences of a pattern
Matches a pattern on a subject. Returns a MatchAllResult
object containing all matches.
/**
* @param string $pattern
* @param string $subject
*
* @return \Spatie\Regex\MatchAllResult
*/
public static function matchAll(string $pattern, string $subject): MatchAllResult
MatchAllResult::hasMatch(): bool
Checks if the pattern matches the subject.
Regex::matchAll('/abc/', 'abc')->hasMatch(); // true
Regex::matchAll('/abc/', 'abcabc')->hasMatch(); // true
Regex::matchAll('/def/', 'abc')->hasMatch(); // false
MatchAllResult::results(): array
Returns an array of MatchResult
objects.
$results = Regex::matchAll('/ab([a-z])/', 'abcabd')->results();
$results[0]->result(); // 'abc'
$results[0]->group(1); // 'c'
$results[1]->result(); // 'abd'
$results[1]->group(1); // 'd'
Replacing a pattern in a subject
Replaces a pattern in a subject. Returns a ReplaceResult
object.
/**
* @param string|array $pattern
* @param string|array|callable $replacement
* @param string|array $subject
* @param int $limit
*
* @return \Spatie\Regex\ReplaceResult
*/
public static function replace($pattern, $replacement, $subject, $limit = -1): ReplaceResult
ReplaceResult::result(): mixed
Regex::replace('/a/', 'b', 'abc')->result(); // 'bbc'
Regex::replace
also works with callables. The callable will receive a MatchResult
instance as it's argument.
Regex::replace('/a/', function (MatchResult $matchResult) {
return str_repeat($matchResult->result(), 2);
}, 'abc')->result(); // 'aabc'
Patterns, replacements and subjects can also be arrays. Regex::replace
behaves exactly like preg_replace
in those instances.
Error handling
If anything goes wrong in a Regex
method, a RegexFailed
exception gets thrown. No need for checking preg_last_error()
.
Testing
$ composer test
Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review [our security policy](../../security/policy) on how to report security vulnerabilities.
Postcardware
You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.
Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.
We publish all received postcards on our company website.
Credits
- Sebastian De Deyne
- [All Contributors](../../contributors)
License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
*Note that all licence references and agreements mentioned in the Regex README section above
are relevant to that project's source code only.