Remove Whitespace from Function Output

In WordPress, there are many functions which output things for you. For example, wp_list_pages() outputs a list of all your published pages. The HTML markup it spits out is pretty nicely formatted (meaning: has line breaks and indenting).

There are some circumstances where all that "whitespace" in the formatting is undesirable. Like 1) it's all the more characters to deliver and 2) closing "the gap" in older versions of IE.

If the function supports a way to return a string (rather than immediately echo it), you can use a regex to remove the space:

<?php
   echo preg_replace('/>\s+</m', '><', wp_list_pages('echo=0'));
?>

Comments

  1. User Avatar
    Benjamin Mayo
    Permalink to comment#

    Or you can just str_replace(‘ ‘, ”, function_to_call()), at about double the speed of a regex.

    • User Avatar
      Joseph Silber
      Permalink to comment#

      This would delete all whitespace characters, rendering your code useless. e.g.:
      <a href="#">Whatever</a>
      will turn into
      <ahref="#">Whatever</a>
      which is pretty much useless.

  2. User Avatar
    Kevin
    Permalink to comment#

    Cool hacks… These should be added to WordPressWiki.com

  3. User Avatar
    Php Programmer
    Permalink to comment#

    Good job…. often an XML input file contains insignificant whitespace like pretty-printed element structures. This is nice to look at, but it adds to the byte length of the file in memory (processing time) and often we don’t want to transfer such whitespace to the output file.

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

Submit a Comment

icon-closeicon-emailicon-linkicon-menuicon-searchicon-tag