RE: [PHP] Re: Replacing a space with an underscore

From: Date: Thu, 01 May 2003 15:44:15 +0000
Subject: RE: [PHP] Re: Replacing a space with an underscore
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-145973@lists.php.net to get a copy of this message
> Mysql: > > SELECT REPLACE(blah,' ','_') as blahWithUnderScore WHERE x=x > > PHP: > > $string = str_replace(" ","_", $string); > $string = preg_replace("/[\s]/","_",$string); > $string = eregi_replace("[[:space:]]","_",$string); > > I would use the mySql way. It's always good to include a reason why, like a benchmark, when you suggest a certain method to use. You should always benchmark your own solutions. If you have a database heavy application, then I wouldn't tax the database with the extra work of taking care of the spaces for you. Using this code: $query1 = 'SELECT c1 FROM test LIMIT 100'; $query2 = 'SELECT REPLACE(c1," ","_") FROM test LIMIT 100'; //Str_Replace Method $result = mysql_query($query1); while($row = mysql_fetch_row($result)) { echo str_replace(' ','_',$row[0]); } //Query Method $result = mysql_query($query2); while($row = mysql_fetch_row($result)) { echo $row[0]; } Achieved these results: Str_Replace Method: 0.00233495235443 (Avg: 0.00253650387128) Query Method: 0.00189101696014 (Avg: 0.00206401030223) (Over 300 iterations.) The test table has 1,000,000 rows in it with 4 different repeated sentences in it similar to: "The question is whether it's faster for the database or PHP to do it though". (Created this table for other benchmarks. :) ---John W. Holmes... PHP Architect - A monthly magazine for PHP Professionals. Get your copy today. http://www.phparch.com/

« previous php.general (#145973) next »