1

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.

2
  • 1
    Just a tip, you don't have to use / as a separator. When your search pattern includes a /, it can improve readability to use a different character and avoid the escaping: #/.+?/# Commented Nov 5, 2015 at 3:28
  • @miken32 Ah yes, good point. I've used this before (for shorter regex'es, ironically) but hadn't thought of using it here. Commented Nov 5, 2015 at 13:47

2 Answers 2

1

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/
    )
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Kevin! This did the trick. I'm accepting your answer.
0

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

Regex101

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.