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 to match a nbsp HTML whitespace?
- How to use PHP regex to match special characters?
- How to use PHP regex to match an XML tag?
- How to match a space using PHP regex?
- How to use PHP regex to match an exact string?
- How to remove a tag from a string using PHP regex?
- How to replace a tag using PHP regex?
- How to remove non-printable characters using PHP regex?
- How to use PHP regex to match a multiline?
- How to use PHP regex to get a YouTube video ID?
See more codes...