Web lists-archives.com

Re: [PHP] Catch line indetation




On 29.10.2016 at 07:40, David Harkness wrote:

> On Fri, Oct 28, 2016 at 7:37 PM, German Geek <geek.de@xxxxxxxxx> wrote:
> 
>> String functions are very fast. Regexes have to be compiled under the hood
>> to take advantage of their speed.
> 
> A lover of assembly language could hand-code a routine to "count leading
> whitespace of all known types" that would blow any other solution away.*
> But every developer who came across it over the next decade would have to
> learn it.**
> 
> Or you can write a function with unit tests so nobody ever has to read the
> gory details again.***
> 
>     /**
>      * Returns the leading whitespace from the given string or an empty
> string for all else.
>      *
>      * @param string $input converted to string if needed
>      * @return string the leading whitespace or empty string if none
>      */
>     function lspace($input) { // psuedably-cryptic c-style function name?
> check!
>         if ($input && ($input = (str) $input)) { // micro-optimization
> alert! no idea if this helps; totally defensive. kill?
>             if (preg_match('/^\s*/', $input, $matches)) { // ignore errors
> like a boss (actually, this is fine here)
>                 return $matches[0];
>             }
>         }
>         return ''; // Ask me a dumb question, get a dumb answer.
>     }
> 
>     [Awesome unit tests here] [1]

Very nice! :-)

> * This could be baked into the regex library too.
> ** You'd wrap it in a function where most readers would never see it.
> *** Did Unicode++ just drop? No problem, the PHP devs will fix preg_match
> and "\s" before you could ever notice. Stay on top of updates!
> **** Asterisk in regex is greedy so there's no need to find the end of the
> whitespace nor capture a portion of the match. Simplify!

Good catch!

> [1] http://ideone.com/PO2Xoq

-- 
Christoph M. Becker



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php