所以我正在获取HTML文件的内容,我想从HTML元素中提取特定信息到多维数组中。 问题是我对正则表达式没有太多经验。
列表中有许多艺术家,这就是每个艺术家的格式。
<li class="artist"><a href="*I NEED THIS PATH*">*AND THIS TEXT*</a></li>
这是我到目前为止所拥有的:
$contents = file_get_contents('somefile.txt');
$artists = preg_split('/^<li class="artist"><a href="(.*)">(.*)</a></li>$/', $contents);
$artistInfo = array();
foreach( $artists as $artist ) :
preg_match('/href="(.*)">/', $element, $matchPath); // link paths
preg_match('/">(.*)</a></li>/', $element, $matchName); // artist names
array_push( $artistInfo, array( $matchName, $matchPath ) ); // put info into array
endforeach;
print_r($artistInfo);
preg_split没有像我希望的那样工作,所以它把其他一切都抛弃了,但我不知道我的preg_match表达是否正确。 请帮忙!
不要为此使用正则表达式。 DOMDocument
是你的朋友:
$artistInfo = array();
$dom = new DOMDocument;
$dom->loadHTML( file_get_contents('somefile.txt') );
$xPath = new DOMXpath($dom);
foreach ( $xPath->query('//li[@class="artist"]/a') as $anchor ) {
$artistInfo[] = array(
$anchor->textContent,
$anchor->getAttribute('href')
);
}
在这里看到它的实际效果:http://codepad.viper-7.com/NziHBo