S
S
Svyatoslav Nemato2016-09-03 03:27:31
PHP
Svyatoslav Nemato, 2016-09-03 03:27:31

How to cut out everything unnecessary from a tag in PHP?

Help with regex, how to strip all content from a div and leave only the style tag
Example:

<div onclick="alert('Hello')" style="color:#ff0000;">текст</div>
<div onclick="alert('Hello')">текст</div>
<div style="color:#ff0000;" onclick="alert('Hello')">текст</div>
<div style="color:#ff0000;">текст</div>

Need to get
<div style="color:#ff0000;">текст</div>
<div>текст</div>
<div style="color:#ff0000;" >текст</div>
<div style="color:#ff0000;"></div>

Stuck at this stage.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
P
Pavel Omelchenko, 2016-09-03
@makklovskiy

Not cut, but reassembled =)

<?php

$HTMLCode = <<< HTML
<div onclick="alert('Hello')" style="color:#ff0000;">текст1</div>
<div onclick="alert('Hello')">текст2</div>
<div style="color:#ff0000;" onclick="alert('Hello')">текст3</div>
<div style="color:#ff0000;">текст4</div>
HTML;

$HTMLCode = mb_convert_encoding($HTMLCode, 'HTML-ENTITIES', "UTF-8");

$dom = new DomDocument();
$dom->loadHTML( $HTMLCode );
$xpath = new DomXPath( $dom );

$_res = $xpath->query(".//div");

foreach($_res as $div){
  $style = $div->getAttribute('style') ? ' style="'.$div->getAttribute('style').'"' : '';
    echo '<div'.$style.'>'.$div->textContent.'</div>';
}

A
Abdula Magomedov, 2016-09-03
@Avarskiy

I suggest looking towards the HTML Purifier library. For these purposes, he
htmlpurifier.org

M
Muhammad, 2016-09-03
@muhammad_97

Better all the same, not a regular expression, but a parser.

Y
yurygolikov, 2016-09-03
@yurygolikov

+ better parser

V
Vitaly, 2016-09-03
@vshvydky

For php, a good static content parser is simple_html_dom

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question