我需要知道如何遍历这个数组并获取html内容,以便我可以使用它来创建另一个数组。我拥有的数组就是:
$arr = array(
"<span class='inside'>inside1</span> this is outside",
"<span class='inside'>inside2</span> this is outside",
"<span class='inside'>inside3</span> this is outside"
);
我希望得到以下结果:
$result = array(
"inside1",
"inside2",
"inside3"
);
我尝试了以下但没有结果:
foreach ( $arr as $html){
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);
$result = $xpath->query('//span[@class="inside"]');
echo $result
}
请帮助。
答案 0 :(得分:1)
你可以这样做
$arr = array(
"<span class='inside'>inside1</span> this is outside",
"<span class='inside'>inside2</span> this is outside",
"<span class='inside'>inside3</span> this is outside"
);
$insideHTML = array();
foreach($arr as $string) {
$pattern = "/<span ?.*>(.*)<\/span>/";
preg_match($pattern, $string, $matches);
$insideHTML[] = $matches[1];
}
var_dump($insideHTML);
这将为您提供以下数组
array(3) {
[0]=>
string(7) "inside1"
[1]=>
string(7) "inside2"
[2]=>
string(7) "inside3"
}
答案 1 :(得分:1)
$arr = array(
"<span class='inside'>inside1</span> this is outside",
"<span class='inside'>inside2</span> this is outside",
"<span class='inside'>inside3</span> this is outside"
);
function clean($var)
{
$var=strip_tags($var);
$chunk=explode(' ',$var);
return $chunk[0];
}
$inside = array_map("clean", $arr);
print_r($inside);
答案 2 :(得分:0)
对于完全示例,这可行:
$arr = array(
"<span class='inside'>inside1</span> this is outside",
"<span class='inside'>inside2</span> this is outside",
"<span class='inside'>inside3</span> this is outside"
);
$inside = array();
foreach($arr as $k=>$v){
$expl1 = explode("<span class='inside'>", $v);
foreach($expl1 as $k2=>$v2){
$v2 = trim($v2);
if(strpos($v2, '</span>') !== false){
$expl2 = explode('</span>', $v2);
$inside[] = $expl2[0];
}
}
}
print_r($inside);
产生:
Array
(
[0] => inside1
[1] => inside2
[2] => inside3
)
答案 3 :(得分:0)
如果这是您唯一需要做的事情(例如,它们总是被构造为<span>Inside</span>Oustide
)您可以这样做:
$result=array();
foreach($arr as $html) {
$result[]=substr(strstr(strstr($html,'>'),'<',true),1);
}