PHP - 将字符串转换为键值数组

Biz*_*oss 1 php regex

我将chars从文本文件转换为键值数组时遇到问题.它忽略了空格.

我的文字是这样的:

type="lorem" template="lorem_ipsum.phtml" key1="lorem Ipsum" key2="lorem Ipsum" key2="lorem Ipsum"
Run Code Online (Sandbox Code Playgroud)

我的preg_match代码中的分隔符附近出现问题,我丢失了key1或key'2值中的秒数字!

preg_match_all("/([^,= ]+)=([^,= ]+)/", $line_Content, $r);
$myarray = array_combine($r[1], str_replace('" ','',$r[2]));
Run Code Online (Sandbox Code Playgroud)

救命!

dec*_*eze 5

此正则表达式应该更好地匹配您的预期文本:

(\w+)="([^"]*)"
Run Code Online (Sandbox Code Playgroud)

一个单词后跟一个等号然后是双引号,然后是下一个双引号的任何内容.

preg_match_all('/(\w+)="([^"]*)"/', $line_Content, $r);
$myarray = array_combine($r[1], $r[2]);
Run Code Online (Sandbox Code Playgroud)

请注意,对于双引号内的双引号,这将失败,此时您需要转义序列,此时正则表达式变得非常麻烦.