PHP - Extracting text from HTML

I have a long HTML string containing

<p> <img> <span> 

and many other tags.

Is there a way to extract ONLY the text inside the tags from this line?

+4
source share
2 answers

If you want to extract all the text into any tags, an easy way is to uncheck: strip_tags ()

If you want to remove specific tags, perhaps this SO question .

+9
source

I know that I will have a lot of mistakes, but for a simple task I seem to be using regular expressions.

 preg_match_all('~(<span>(.*?)</span>)~', $html, $matches); 

$matches[0] will contain all span tags and their contents, $matches[1] contains only content.

For more complex things, you can take a look at PHP Simple HTML DOM Parser or similar:

 // Create DOM from URL or file $html = str_get_html($html); // Find all images foreach($html->find('img') as $element) { echo $element->src . '<br>'; } 

Etc.

+1
source

Source: https://habr.com/ru/post/1301560/


All Articles