I have HTML code like:
<div class="wrap"> <div> <div id="hmenus"> <div class="nav mainnavs"> <ul> <li><a id="nav-questions" href="/questions">Questions</a></li> <li><a id="nav-tags" href="/tags">Tags</a></li> <li><a id="nav-users" href="/users">Users</a></li> <li><a id="nav-badges" href="/badges">Badges</a></li> <li><a id="nav-unanswered" href="/unanswered">Unanswered</a></li> </ul> </div> </div> </div> </div>
How do I remove whitespace between tags by PHP?
We should get:
<div class="wrap"><div><div id="hmenus"><div class="nav mainnavs"><ul><li><a id="nav-questions" href="/questions">Questions</a></li><li><a id="nav-tags" href="/tags">Tags</a></li><li><a id="nav-users" href="/users">Users</a></li><li><a id="nav-badges" href="/badges">Badges</a></li><li><a id="nav-unanswered" href="/unanswered">Unanswered</a></li></ul></div></div></div></div>
We can also remove white space by setting parent element font-size to 0 and child elements font-size to 17px .
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
$html = preg_replace('~>\s+<~', '><', $html);
But I don't see the point of this. If you're trying to make the data size smaller, there are better options.
It's been a while since this question was first asked but I still see the need to post this answer in order to help people with the same problem.
None of these solutions were adoptabe for me therefore I've came up with this solution: Using output_buffer
.
The function ob_start
accepts a callback as an argument which is applied to the whole string before outputting it. Therefore if you remove whitespace from the string before flushing the output, there you're done.
/** * Remove multiple spaces from the buffer. * * @var string $buffer * @return string */ function removeWhitespace($buffer) { return preg_replace('/\s+/', ' ', $buffer); } ob_start('removeWhitespace'); <!DOCTYPE html> <html> <head></head> <body></body> </html> ob_get_flush();
The above would print something like:
<!DOCTYPE html> <html> <head> </head> <body> </body> </html>
Hope that helps.
HOW TO USE IT IN OOP
If you're using object-orientated code in PHP you may want to use a call-back function that is inside an object.
If you have a class called, for instance HTML, you have to use this code line
ob_start(["HTML","removeWhitespace"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With