D
D
Dmitry Gusev2021-09-02 12:46:24
PHP
Dmitry Gusev, 2021-09-02 12:46:24

Finding and removing specific HTML tags with php?

Good afternoon!

Please help me solve the following problem correctly:

There is a php parser with simple html dom.
There is a parsed part of the main content, it lies in the $posts['content'] array

Task:

The parsed part of $post['content'] contains, among other things, the following html:

<img itemprop="url image" loading="lazy" class="vc_single_image-img attachment-large" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20690%20808'%3E%3C/svg%3E" width="690" height="808" data-lazy-sizes="(max-width: 690px) 100vw, 690px" data-lazy-src="/images/wp-content/uploads/2021/03/deklaracija-list-1.jpg">
<img itemprop="url image" loading="lazy" class="vc_single_image-img attachment-large" src="/images/wp-content/uploads/2021/03/deklaracija-list-1.jpg" width="690" height="808" data-lazy-sizes="(max-width: 690px) 100vw, 690px">


you need to find and remove the tag along with the content containing . In the above example - delete the first img Clarifications: img can be a different number of img src=data: further - dynamic Which PHP function can do this and how to use it? Tried str_replace and preg_replace - no luck Thanks in advance! <img *. src=data: .*>




Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Zolin, 2021-09-02
@dm_gusev

With Simple HTML Dom and do

$content = '<img itemprop="url image" loading="lazy" class="vc_single_image-img attachment-large" src="data:image/svg+xml,%3Csvg%20xmlns=\'http://www.w3.org/2000/svg\'%20viewBox=\'0%200%20690%20808\'%3E%3C/svg%3E" width="690" height="808" data-lazy-sizes="(max-width: 690px) 100vw, 690px" data-lazy-src="/images/wp-content/uploads/2021/03/deklaracija-list-1.jpg">
<img itemprop="url image" loading="lazy" class="vc_single_image-img attachment-large" src="/images/wp-content/uploads/2021/03/deklaracija-list-1.jpg" width="690" height="808" data-lazy-sizes="(max-width: 690px) 100vw, 690px">';

$html = str_get_html( $content );
$images = $html->find( 'img' );

foreach ( $images as $key => $image ) {
  if ( stripos( $image->src, 'data:' ) !== false ) {
    $image->outertext = '';
  }
}

var_dump( $html->innertext );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question