So I know how to extract text from a php string when it is cleanly separated by two different characters (ie. [abc])...
However, I am now facing a problematic situation where I need to extract text that is located between two instances of the same character ('/'). What makes it even trickier is that this can happen multiple times within the same string.
An example should help make this clearer:
"This is /a/ silly ex/amp/le of what I /me/an."
In this case, I would want to grab 'a', 'amp' and 'me'
.
These examples show the variety of cases I might run into (different lengths and cases where I'm not grabbing a whole word but letters within a word).
What I've tried:
('/(\/.+?)+(\/)/i')
But this, as expected, captures everything between the first and last slashes. The ideal would be a way to match until the NEXT occurrence of a slash, rather than the last one...
I've been googling this for quite some time, but am only coming up with cases with two different delimiters.
You can use preg_match_all
to get multiple matches.
$string = 'This is /a/ silly ex/ampl/e of what/ I me/an';
$regex = '/\/.+?\//';
preg_match_all($regex, $string, $matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => /a/
[1] => /ampl/
[2] => / I me/
)
)
Try this:
(\/)(.*?)\1
What is inside of (\/)
will be what you're matching between. For example, matching between a set of *
would look like this:
(\*)(.*?)\1