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 match a double quote in PHP regex?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match a year?
- How to get last matched occurrence in PHP regex?
- How to use PHP regex to match an exact string?
- How to match a space using PHP regex?
- How to remove a tag from a string using PHP regex?
- How to use PHP regex to match time?
- How to match a quotation mark in PHP regex?
See more codes...