【问题标题】:What is the error in my own PHP regex code?我自己的 PHP 正则表达式代码有什么错误?
【发布时间】:2023-06-10 20:03:01
【问题描述】:

今天,我在这里阅读了有关 Stack Overflow 的问题:https://*.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 正则表达式代码有什么错误?

【问题讨论】:

    标签: php regex string


    【解决方案1】:

    你需要使用:

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

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

    【讨论】: