0

Hi how to excerpt this code using php ?

It's the wordpress content . but there is not this way in wordpress

From

<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>
.
.
.

To

<div class='first'>first</div>
<div class='second'>second</div>
danial dezfooli
  • 788
  • 2
  • 9
  • 27

2 Answers2

2

you can try this using 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);
miglio
  • 2,048
  • 10
  • 23
  • I don't think this regex should work, if you want to match all the div's content you can use `/
    (.*?)<\/div>/`. See https://regex101.com/r/cX4kS8/1
    – vard Aug 19 '15 at 14:34
  • @vard have you executed the php? – miglio Aug 19 '15 at 14:36
  • @vard preg_replace_callback get a loop of matches from pattern. – miglio Aug 19 '15 at 14:38
  • Just did, it indeed work. My bad, I got confused by the fact that the regex seemed to match the class name + the content. – vard Aug 19 '15 at 14:42
0

You could hide the div after the second one with the following css:

div.first, div.second {
    display: none;
}
div.first:first-child,
div.second:first-child {
    display: block;
}

To remove completely the divs from the markup in PHP you should need regex, but parsing HTML in a regex can lead to terrible results.

If you really need to go in that way, you should better consider to store your div's content in different fields.

Community
  • 1
  • 1
vard
  • 4,057
  • 2
  • 26
  • 46