简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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