在php字符串中查找相同的两个字符之间的文本
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.
所以我知道如何从php字符串中提取文本,当它被两个不同的字符干净地分开时(即。[ abc])... p>
但是,我现在面临一个问题,我需要提取位于同一个字符('/')的两个实例之间的文本。 甚至更棘手的是,这可能会在同一个字符串中多次发生。 p>
一个例子应该有助于使这个更清晰: p>
“这是/ a /傻傻的ex / amp / le我的/me/an."
nn在这种情况下,我想抓住 这些例子显示了我可能遇到的各种案例(不同的长度和案例,我没有抓住一个 整个单词,但单词中的字母)。 p>
我尝试了什么: p>
但是,正如预期的那样,它会捕获第一个和最后一个斜杠之间的所有内容。 理想的是匹配直到NEXT出现斜杠的方式,而不是最后一个...... p>
我一直在谷歌搜索这段时间,但我只是来了 具有两个不同分隔符的案例。 p>
div> 'a','amp'和'me' code>。 p>
('/(\ /.+?) +(\ /)/ i')
code> pre>
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