How to convert a piece of HTML code to plain text in PHP?

How to convert a piece of HTML code to plain text without leading and ending spaces in PHP?

For example, I would like to convert

<div> <b>hello</b> world</div>

to a string

hello world

You may use this piece of code in PHP to strip HTML tags, remove leading and ending spaces and convert special characters to HTML entities (if you put this into an HTML page):

$linetxt = htmlspecialchars(trim(strip_tags($line)));

An example:

$ php -a
Interactive shell

php > echo htmlspecialchars(trim(strip_tags('<div> <b>hello</b> world</div>'))) . PHP_EOL;
hello world
php > 

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

One comment:

Leave a Reply

Your email address will not be published. Required fields are marked *