我拥有的文本:
URL: http://example.com
Type: department
Empty value:
Contact Name: John Doe
...
我想要一个这样的数组:
array(
'url' => 'http://example.com',
'type' => 'department',
'empty-value' => '',
'contact-mame' => 'John Doe'
)
我在做类似的事情
preg_match_all( '/(url|type): (.*)/i', $string, $match );
但是$match的值没有按我需要的顺序排列,我也不知道如何获取密钥。
此时,转换为小写键和短划线并不重要。
你能建议任何正则表达式模式吗?
非常感谢。
您可以使用preg_match_all
和array_combine
:
$s = <<< EOF
URL: http://example.com
Type: department
Empty value:
Contact Name: John Doe
EOF;
preg_match_all('~^([^:]+):'h*(.*)$~m', $s, $matches);
$output = array_combine ( $matches[1], $matches[2] );
print_r( $output );
输出:
Array
(
[URL] => http://example.com
[Type] => department
[Empty value] =>
[Contact Name] => John Doe
)