简体   繁体   English

PHP RegEx基于模式创建关联数组

[英]PHP RegEx create an associative array based on pattern

I have this string: 我有这个字符串:

$str = '<td class="title">Genre:</td><td class="detail"><a href="/en-us/store/browse/action">   Action   </a></td></tr>';
$str2 = '<td class="title">Release Date:</td><td class="detail">   January 13 2009  </td></tr>';

I need to get an associative array structured like this: 我需要获得一个结构如下的关联数组:

$arr[$title] = $detail;

My problem is not the pattern itself, but how to create an array. 我的问题不是模式本身,而是如何创建数组。 Thanks for any help. 谢谢你的帮助。

If your regexp is like this 如果您的正则表达式是这样的

$re = '~<td class="title">(.+?):</td><td class="detail">(.+?)</td>~';

then you can simply do 那你就可以做

preg_match($re, $str, $matches);
$arr[$matches[1]] = $matches[2];

Do note however, that regexes is not the best way to parse html. 但是请注意,正则表达式不是解析html的最佳方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM