Cut html string by keeping html tags as it is

12 04 2009

With the use of WYSIWYG editor user can enter html content. While displaying teaser(short content) of the content on home page or dashboard it is hard to cut the string properly. Regarding this I did not see any available code. I need to do this in javascript and PHP. I implemented same logic in both javascript and php. I hope it would be helpful for others. The code for javascript and php is available at http://code.google.com/p/cut-html-string/

Using PHP code

You can download PHP code from this link
Download code and extract it. Include the cutstring.php file and use like this

$data = "<span style='color:green;'>aa<em>BB</em><ul><li>one</li><li>two</li><li>three</li></ul></span>";
$wanted_count = 10;
$cutstrObj = new HtmlCutString($data,$wanted_count);
$new_string = $cutstrObj->cut();
echo $new_string;

Update: We can directly use cut_html_string function

$data = "<span style='color:green;'>aa<em>BB</em><ul><li>one</li><li>two</li><li>three</li></ul></span>";
$wanted_count = 10;
$new_string = cut_html_string($data,$wanted_count);
echo $new_string;

Update 2: Above code will output the following string

<span style="color:green;">aa<em>BB</em><ul><li>one</li><li>two</li></ul></span>

Using Javascript code

You can downlod javascript code from this link
Download code and extract it. Include the cutstring.js file in your html file and use like this.

var data = '<span style="font-weight:bold">aa<em>BB</em></span><span id="1">Test <b>Cutstring</b></span> bb';
var wanted_count = 10;
var cutstrObj = new CutString(data,wanted_count);
var newStr = cutstrObj.cut();
console.log(newStr);

update: Now we can directly use cutHtmlString function

var data = '<span style="font-weight:bold">aa<em>BB</em></span><span id="1">Test <b>Cutstring</b></span> bb';
var wanted_count = 10;
var newStr = cutHtmlString(data, wanted_count);
console.log(newStr);

Update 2: Above code will log the following output

<span style="font-weight: bold;">aa<em>BB</em></span><span id="1">Test <strong>C</strong></span>

First I implemented it easily in javascript using DOM. But it took lot of time in PHP to implement same logic. Finally I implemented same logic using DOMDocument in php.

Advertisements