php-regexHow to use capture group in PHP regex?
Capture groups are used to group parts of a regular expression together and can be used to extract parts of a string. In PHP, capture groups are denoted by parentheses () and can be accessed using the $matches array.
Example code
$string = 'This is a string';
$pattern = '/This (is) a string/';
preg_match($pattern, $string, $matches);
Output example
Array
(
[0] => This is a string
[1] => is
)
Code explanation
$string: The string to be matched against the regular expression.$pattern: The regular expression pattern, including capture groups denoted by parentheses().preg_match(): The PHP function used to match a string against a regular expression pattern.$matches: The array that will contain the results of the match.
Helpful links
More of Php Regex
- How to use PHP regex to match a zip code?
- How to match a quotation mark in PHP regex?
- How to use PHP regex to match a year?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match special characters?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match UUID?
See more codes...