> > Very true, I agree. For your solution, though, wouldn't it correctly
> match a
> > string such as '2,3,11,12' even though there is no entry that's just
> one?
> 
> Ok, why not something like this..
> There is almost always a better solution than regex
> 
> <?php
> 
> $string = '98,244,9,243,2,6,36,3,111,';
> 
> if(catchOne($string) == 'TRUE'){
>         echo 'Found a One';
>         }else{
>         echo 'No match found';
>         }
> 
> function catchOne($string){
> 
>   $arr = explode(',', $string);
> 
>   // check if the 1 is in the array
>   if(in_array('1', $arr)){
>         return TRUE;
>         }else{
>         return FALSE;
>         }
> }

I love it when questions like this come up. Honestly, you can use any
solution you want and it's not going to make that much of a difference.
But... it's always fun to benchmark them all and see which one wins. 

Here's the code I tried (which uses PEAR Benchmark)

$str = '1,2,3,4,5,6,7,8,9,0';

$timer->start();
if(preg_match('/(^|,)1(,|$)/',$str)) {}
$timer->setMarker('Preg');
if(in_array('1',explode(',',$str))) {}
$timer->setMarker('Explode');
if(strstr($str,',1,') || substr($str,0,2)=='1,' ||
substr($str,-2)==',1') {}
$timer->setMarker('Strstr');
$timer->stop();
$timer->display();

and, the results...

Method  Elapsed Time
------------------------
Preg            0.000080
Explode         0.000065
Strstr  0.000065

Make your own conclusions... 

Since the last solution actually uses three tests, it is even faster
overall when the first condition comes out true and then gets slower if
it has to check the second and then third condition. So, putting
whatever condition is true the majority of the time will make that
solution more efficient. 

---John Holmes...



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

Reply via email to