你如何返回php正则表达式的实际匹配结果

你如何返回php正则表达式的实际匹配结果

问题描述:

I have a string and need to get a specific chunk of text out of it. That chunk is always going to be wrapped in a known quantity of of other text, so its easy to use a regular expression to find the desired chunk via its surroundings. In php, what is the best way to do this? I've read through the man pages of various functions that deal with regular expressions, but almost all of them seem to return the number of matches, but not the match itself.

My goal is to get the results of the match, then use preg_replace to get rid of the known quantity and leave me with the desired text.

我有一个字符串,需要从中获取一段特定的文本。 该块总是被包含在已知数量的其他文本中,因此它易于使用正则表达式来通过其周围环境找到所需的块。 在PHP中,最好的方法是什么? 我已经阅读了处理正则表达式的各种函数的手册页,但几乎所有函数都返回匹配数,但不是匹配本身。 p>

我的目标是 得到匹配的结果,然后使用preg_replace去掉已知的数量,并留下我想要的文本。 p> div>

if (!preg_match('/foo (expression) bar/', $text, $matches)) {
    // text didn't match!
}

echo $matches[1];

You pass an extra variable as the third parameter to preg_match, here $matches. $matches[0] will contain the whole regex match, matches[1] the first () group, $matches[2] the second () group etc.