什么是错误在我自己的PHP正则表达式代码


What is the error in my own PHP regex code?

今天,我在这里看到了一个关于堆栈溢出的问题:https://stackoverflow.com/questions/32151810/how-to-parse-this-text-block-into-variables-by-php

我已经尝试过这样做了:

preg_match("/([a-zA-Z_]+)/", "[first_text] = [second_text, third_text] : [forth_text, fifth_text]", $matches);

当我测试它时,它不能正常工作:

echo $matches[0];
echo $matches[1];
echo $matches[2];
echo $matches[3];
echo $matches[4];

将打印:

first_textfirst_text

什么是错误在我自己的PHP正则表达式代码?

您需要使用:

preg_match_all('/([a-zA-Z_]+)/', "[first_text] = [second_text, third_text] : [forth_text, fifth_text]", $matches);

preg_match_all将使用您的正则表达式返回所有匹配,而preg_match只给您第一个匹配。