Sometimes, we want to get a substring between two strings in PHP.
In this article, we’ll look at how to get a substring between two strings in PHP.
How to get a substring between two strings in PHP?
To get a substring between two strings in PHP, we can use the preg_match
function.
For instance, we write
$str = "before-str-after";
if (preg_match("/before-(.*?)-after/", $str, $match) == 1) {
echo $match[1];
}
to call preg_match
with a regex that matches the string between 'before-'
and '-after'
.
And we check for matches in the $str
string.
We get the match from the $match
array.
If preg_match
returns 1, then a match is found.
Conclusion
To get a substring between two strings in PHP, we can use the preg_match
function.