Skip to content

Instantly share code, notes, and snippets.

@tnrn9b
Forked from gskema/html_trim_whitespace.php
Created August 4, 2018 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tnrn9b/379ef642be27b71dadacd852aa91f323 to your computer and use it in GitHub Desktop.
Save tnrn9b/379ef642be27b71dadacd852aa91f323 to your computer and use it in GitHub Desktop.
HTML whitespace trim RegEx (regular expression) for PHP. Useful for trimming HTML content before TCPDF processing.
<?php
// Trims whitespaces after any tags. Assumes that a tag ends with '/>', '\w>', '">'.
$html = preg_replace('#(["|\/|\w]>)(\s+)#', '$1', $html);
// Trims whitespaces before any tags. Assumes that tags start with '<\w+'
$html = preg_replace('#(\s+)(<\/?\w+)#', '$2', $html);
// Trims spaces between tags (both opening and closing).
// Assumes that a tag ends with '/>', '\w>', '">' and starts with '<\w+'
$html = preg_replace('#(["|\/|\w]>)(\s+)(<\/?\w+)#', '$1$3', $html);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment