Re: breaking up a string (every N chars)
| From: | Evan Nemerson | Date: | Tue, 27 May 2003 05:14:31 +0000 |
| Subject: | Re: breaking up a string (every N chars) | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-149049@lists.php.net to get a copy of this message | ||
I think my way is fastest for short strings (< about 90000 chars on my box),
John's for long strings.
$ php -q test.php 300
John: 0.0012029409408569
Evan: 0.00058400630950928
Justin: 0.0025380849838257
$ php -q test.php 90000
John: 0.20975005626678
Evan: 0.21145403385162
Justin: 0.86533498764038
$ php -q test.php 300000
John: 0.71977400779724
Evan: 1.8892879486084
Justin: 4.4126880168915
my test.php:
<?php
function getmicrotime() {
list($usec, $sec) = explode(" ", microtime());
return ( (float)$usec + (float)$sec );
}
$x = 0;
$s = '';
$a = array();
for ( $x = 0 ; $x < $_SERVER['argv'][1] ; $x++ ) {
$s .= (string)mt_rand(0, 9);
}
echo "John: ";
$t = getmicrotime();
preg_match_all('/.{3}/',$s, $a);
echo getmicrotime()-$t."\n";
$a = array();
echo "Evan: ";
$t = getmicrotime();
$a = explode("\n", trim(chunk_split($s, 3, "\n"), "\n"));
echo getmicrotime()-$t."\n";
$a = array();
echo "Justin: ";
$t = getmicrotime();
$x = 0;
while ( $x < (strlen($s)-2) )
$a[] = substr($x+=3, 3);
echo getmicrotime()-$t."\n";
$a = array();
?>
On Monday 26 May 2003 07:49 pm, John W. Holmes wrote:
> Can also use:
>
> preg_match_all('/.{3}/',$String,$ar);
>
> $ar[0] will be your array of matches.
>
> Array
> (
> [0] => Array
> (
> [0] => 001
> [1] => 102
> [2] => 203
> [3] => 304
> [4] => 405
> )
>
> )
>
> (shown to be slightly faster than the below in my tests, but do your own
> benchmarks)
>
> ---John W. Holmes...
>
> PHP Architect - A monthly magazine for PHP Professionals. Get your copy
> today. http://www.phparch.com/
>
> > -----Original Message-----
> > From: Evan Nemerson [mailto:evan@coeus-group.com]
> > Sent: Monday, May 26, 2003 9:46 PM
> > To: php-general@lists.php.net
> > Subject: Re: [PHP] breaking up a string (every N chars)
> >
> > php.net/chunk_split
> > php.net/explode
> >
> > explode("\r\n", trim(chunk_split($String, 3, "\r\n")));
> >
> > On Monday 26 May 2003 06:16 pm, zavaboy wrote:
> > > Hi, How can I break a string every N (eg: 3) characters?
> > >
> > > //Suppose I have a string...
> > > $String = "001102203304405";
> > > //Now, how do I break this string every 3 characters?
> > > //So...
> > > $String[0] = "001";
> > > $String[1] = "102";
> > > $String[2] = "203";
> > > $String[3] = "304";
> > > $String[4] = "405";
> > >
> > > Thanks in advance!
> >
> > --
> > PHP General Mailing List (http://www.php.net/)
> > To unsubscribe, visit: http://www.php.net/unsub.php
--
Never exceed your rights, and they will soon become unlimited.
-Rousseau