您好如何使用php摘录此代码?
这是wordpress内容。 但在wordpress中没有这种方式
发件人
<div class='first'>first</div>
<div class='second'>second</div>
<div class='first'>first</div>
<div class='second'>second</div>
<div class='first'>first</div>
<div class='second'>second</div>
.
.
.
要
<div class='first'>first</div>
<div class='second'>second</div>
答案 0 :(得分:2)
您可以使用preg_replace_callback尝试此操作:
//if html is retrieved in a variable like $html, then
$html = "<div class='first'>first</div>
<div class='second'>second</div>
<div class='first'>first</div>
<div class='second'>second</div>
<div class='first'>first</div>
<div class='second'>second</div>";
$validate = array('first'=>true,'second'=>true);
$response = trim(preg_replace_callback('/<div\s?.*\/div>/',function($match)use(&$validate){
reset($validate);$key = key($validate);
if(strstr($match[0],$key) != false && $validate[$key] == true){
$validate[$key] = false;
return $match[0];
}
next($validate);$key = key($validate);
if(strstr($match[0],$key) != false && $validate[$key] == true){
$validate[$key] = false;
return $match[0];
}
},$html));
var_dump($response);
答案 1 :(得分:0)
您可以使用以下css隐藏第二个之后的div:
div.first, div.second {
display: none;
}
div.first:first-child,
div.second:first-child {
display: block;
}
要从PHP中的标记中完全删除div,您应该需要正则表达式,但parsing HTML in a regex can lead to terrible results。
如果你真的需要这样做,最好考虑将你的div内容存储在不同的领域。