通过爆炸功能获取标签a的内容

时间:2014-08-17 15:22:25

标签: php explode

我有内容:

<a href="/dien-vien/Chris-Pratt">Chris Pratt</a>,<a href="/dien-vien/Vin-Diesel"> Vin Diesel</a>,<a href="/dien-vien/Bradley-Cooper"> Bradley Cooper</a>

我想要返回字符串:Chris Pratt,Vin Diesel,Bradley Cooper

我尝试代码:

$actor = explode(',', $actor[0]);
$count_actor = count($actor);

for ($i=0; $i < $count_actor; $i++) { 
    $actor = explode('">', $actor[$i]);
    $actor = explode('</a>', $actor[1]);
    $actor .= $actor[0].",";
}

我只得到:数组,

请大家帮助我。

1 个答案:

答案 0 :(得分:3)

使用DOMDocument API

更好地解析HTML
<?php

$html = '<a href="/dien-vien/Chris-Pratt">Chris Pratt</a>,<a href="/dien-vien/Vin-Diesel"> Vin Diesel</a>,<a href="/dien-vien/Bradley-Cooper"> Bradley Cooper</a>';

$doc = new DOMDocument();
$doc->loadHTML($html);

$tags = $doc->getElementsByTagName('a');

$actors = array();
foreach ($tags as $tag) {
       array_push($actors, trim($tag->nodeValue));
}

echo implode(',', $actors); // Chris Pratt,Vin Diesel,Bradley Cooper