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

时间:2015-08-22 06:34:56

标签: php regex string

今天,我已经在Stack Overflow上阅读了一个问题: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正则表达式代码中的错误是什么?

1 个答案:

答案 0 :(得分:3)

您需要使用:

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

preg_match_all会使用你的正则表达式返回所有匹配,而preg_match只会给你第一次匹配。