php-regexHow to use named capture groups in PHP regex?
Named capture groups are a powerful feature of regular expressions in PHP. They allow you to capture parts of a string and assign them to a variable. This makes it easier to work with the captured data.
Example code
$string = 'This is a string';
preg_match('/This is (?<capture>\w+)/', $string, $matches);
echo $matches['capture'];
Output example
a
Code explanation
preg_match()
: This is a PHP function that takes a regular expression and a string as arguments and returns an array of matches.(?<capture>\w+)
: This is the named capture group. It captures one or more word characters and assigns them to the variablecapture
.$matches['capture']
: This is how you access the captured data.
Helpful links
More of Php Regex
- How to use PHP regex to match special characters?
- How to use PHP regex to match a zip code?
- How to get the first match when using regex in PHP?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match an exact string?
- How to use PHP regex to get a YouTube video ID?
- How to match a single quote in PHP regex?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match UUID?
See more codes...