DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Truncate Text Preserving HTML Tags With PHP

Snippets Manager user avatar by
Snippets Manager
·
Mar. 30, 09 · · Code Snippet
Like (0)
Save
Tweet
2.79K Views

Join the DZone community and get the full member experience.

Join For Free
Truncate/limit text preserving the HTML tags (the code auto-closes the tags).


Example


echo String::truncate('jonas', 3, '...'); //jo<...
echo String::truncate('jonas', 3, '...', true); //jon...
echo String::truncate('jonas', 3, '...', true, false); //jon...



Code


//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

class String{
	public static function truncate($s, $l, $e = '...', $isHTML = false){
		$i = 0;
		$tags = array();
		if($isHTML){
			preg_match_all('/<[^>]+>([^<]*)/', $s, $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
			foreach($m as $o){
				if($o[0][1] - $i >= $l)
					break;
				$t = substr(strtok($o[0][0], " \t\n\r\0\x0B>"), 1);
				if($t[0] != '/')
					$tags[] = $t;
				elseif(end($tags) == substr($t, 1))
					array_pop($tags);
				$i += $o[1][1] - $o[0][1];
			}
		}
		return substr($s, 0, $l = min(strlen($s),  $l + $i)) . (count($tags = array_reverse($tags)) ? '' : '') . (strlen($s) > $l ? $e : '');
	}
}
PHP HTML Truncate (SQL)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • A Guide to Events in Vue
  • Image Classification Using SingleStore DB, Keras, and Tensorflow
  • Top 20 Git Commands With Examples
  • Building a Kotlin Mobile App with the Salesforce SDK, Part 3: Synchronizing Data

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo