• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 230
  • Last Modified:

Remove mutiple characters from string.

I need to remove a few different characters from values returned through a mysql databases.

Characters to remove: period (.), underscore (_), single quote (')

I need to know the fastest way to do it:

1. using str_replace 3 times on each word selected from db
2. using mysql's REPLACE function 3 times when selecting from db
3. or is there a better way
0
itcdr
Asked:
itcdr
  • 5
  • 3
1 Solution
 
alextr2003frCommented:
0
 
itcdrAuthor Commented:
What would be the fastest:

1. str_replace
$word=str_replace("_","",$word);
$word=str_replace("\.","",$word);
$word=str_replace("\'","",$word);

2. REPLACE (mysql)
SELECT REPLACE(REPLACE(REPLACE(word,'_',''),'.',''),"'",'') FROM ...

3. preg_replace
$patterns[0] = '/\./';
$patterns[1] = '/_/';
$patterns[2] = '/\'/';
$word=preg_replace($patterns,"",$word);

4. Or is there a better way?
0
 
alextr2003frCommented:
usually string functions are faster than regular expressions but maybe you should try to benchmark and see the results
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
alextr2003frCommented:
to make your preg_replace shorter :
<?php
  $str = ' A string containing . _ \' is here ';
  $newstr = preg_replace("/[\.\_\']/","",$str);
  echo $newstr;
?>
0
 
itcdrAuthor Commented:
How do I benchmark the results?
0
 
alextr2003frCommented:
one variant :
<?php
$stimer = explode( ' ', microtime() );
$stimer = $stimer[1] + $stimer[0];

//your code

$etimer = explode( ' ', microtime() );
$etimer = $etimer[1] + $etimer[0];
echo 'Took '.($etimer-$stimer).' seconds.';
?>
0
 
itcdrAuthor Commented:
Thanks. It turns out the preg_replace was the fastest and the easiest.
0
 
alextr2003frCommented:
you are welcome :)
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 5
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now