php-regexHow to extract a group when using regex in PHP?
Regex (regular expressions) can be used to extract a group of characters from a string in PHP.
$string = 'This is a string';
preg_match('/This (.*) string/', $string, $matches);
echo $matches[1];
The output of the above code will be:
is a
Code explanation
$string = 'This is a string';- This is the string from which the group will be extracted.preg_match('/This (.*) string/', $string, $matches);- This is the regex expression used to extract the group. The(.*)part of the expression is the group that will be extracted.echo $matches[1];- This will output the extracted group.
Helpful links
More of Php Regex
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match special characters?
- How to match a quotation mark in PHP regex?
- How to use PCRE in PHP regex?
- How to use PHP regex lookahead?
- How to use regex in PHP to match dot character?
- How to use PHP regex to match time?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match a URL in a href attribute?
See more codes...