MW

Tag trim

Recent Posts

PHP "is_whitespace" performance (February 12, 2009)

Easy question: What is the fastest way to determine if a string in PHP is whitespace-only?

Easy answer: ![preg_match](http://www.php.net/preg_match)('[^\s]', $string);

Read on for the explanation:

I applied the codeblocks feature of my profile.class.php, here’s the testcase:

    <?php
    require 'profile.class.php';
     
    $iterations = 10000;
     
    profile::codeblocks(array(
      'trim(long string) == ""' => 'trim($long) == ""',
      'trim(long string) === ""' => 'trim($long) === ""',
      'rtrim(long string) == ""' => 'rtrim($long) == ""',
      'rtrim(long string) === ""' => 'rtrim($long) === ""',
      'ltrim(long string) == ""' => 'ltrim($long) == ""',
      'ltrim(long string) === ""' => 'ltrim($long) === ""',
      '!preg_match("[^\s]", long string)' => '!preg_match("[^\s]", $long)',
      'ctype_space(long string)' => 'ctype_space($long)',
      'trim(short string) == ""' => 'trim($short) == ""',
      'trim(short string) === ""' => 'trim($short) === ""',
      'rtrim(short string) == ""' => 'rtrim($short) == ""',
      'rtrim(short string) === ""' => 'rtrim($short) === ""',
      'ltrim(short string) == ""' => 'ltrim($short) == ""',
      'ltrim(short string) === ""' => 'ltrim($short) === ""',
      '!preg_match("[^\s]", short string)' => '!preg_match("[^\s]", $short)',
      'ctype_space(short string)' => 'ctype_space($short)',
    ), array(
      'long' => str_repeat(" \n\t ", 500) . "a" . str_repeat(" \n\t ", 500),
      'short' => str_repeat(" \n\t ", 5) . "a" . str_repeat(" \n\t ", 5),
    ), $iterations);
     
    profile::print_results(profile::flush());

continue reading...