April 19, 2011

PHP: Display the first 500 characters of HTML

Question by Vin

I have a huge HTML code in a php variable like :

$html_code = '<div class="contianer" style="text-align:center;">The Sameple text.</div><br><span>Another sample text.</span>....';

I want to display only first 500 characters of this code. This character count must consider the text in HTML tags and should exclude HTMl tags and attributes while measuring the length.
but while triming the code, it should not affect DOM structure of HTML code.

How can i do it in PHP?
Is there any tuorial or working examples available?
Kindly help!!

Answer by Starx

If its the text you want, you can do this with the following too

substr(strip_tags($html_code),0,500);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!