PHP 使用 preg_match_all 从字符串中提取属性名称

PHP use preg_match_all to extract attribute names from string

我正在使用以下代码将字符串拆分为匹配数组:

$text = 'text required name="first_name" label="First Name"';
preg_match_all('/"(?:\\.|[^\\"])*"|[^\s"]+/', $text, $matches);
print_r($matches);

结果是:

Array
(
    [0] => Array
        (
            [0] => text
            [1] => required
            [2] => name=
            [3] => "first_name"
            [4] => label=
            [5] => "First Name"
        )

)

但我需要的结果是:

Array
(
    [0] => Array
        (
            [0] => text
            [1] => required
            [2] => name="first_name"
            [3] => label="First Name"
        )

)

我试过了,但没用:

preg_match_all('/="(?:\\.|[^\\"])*"|[^\s"]+/', $text, $matches);

谁能告诉我哪里出错了?谢谢

您可以在 preg_split() 中使用模式 /\s(?![\w\s]+\")/ 将字符串拆分为不在值中的 space。

$res = preg_split("/\s(?![\w\s]+\")/", $text);

检查结果 demo

如果你想使用 preg_match_all 这里有一个工作代码:

$text = 'text required name="first_name" label="First Name"';
preg_match_all('([a-zA-Z_]*[=]["][a-zA-Z_]*["]|[a-zA-Z_]*[=]["][ a-zA-Z]*["]|[a-zA-Z]+)', $text, $matches);
print_r($matches);