tags:

views:

97

answers:

2

Just migrating from PHP 5.2 to 5.3, lot of hard work! Is the following ok, or would you do something differently?

$cleanstring = ereg_replace("[^A-Za-z0-9]^[,]^[.]^[_]^[:]", "", $critvalue);

to

$cleanstring = preg_replace("[^A-Za-z0-9]^[,]^[.]^[_]^[:]", "", $critvalue);

Thanks all

+1  A: 

I'm not that familiar with the ereg_* functions but your preg version has a couple of problems:

  1. ^ means beginning of string so with it in the middle it won't match anything; and
  2. You need to delimit your regular expression;

An example:

$out = preg_replace('![^0-9a-zA-Z]+!', '', $in);

Note I'm using ! to delimit the regex but you could just as easily use /, ~ or whatever. The above removes everything except numbers and letters.

See Pattern Syntax, specifically Delimiters.

cletus
Ah I see, so how would I match the ",._:" etc? This was written a while ago, I think I am trying to clean strings and keep everything a-z, A-Z, Number and ",._:" - everything else can be chucked away!
Abs
Regex characters need to be escaped (put a \ before them). This applies to |[]()-*+?{}^$\, the delimiter character and possibly others I'm forgetting.
cletus
+1  A: 

As a follow-up to cletus's answer:

I'm not familiar with the POSIX regex syntax (ereg_*) either, but based on your criteria the following should do what you want:

$cleanstring = preg_replace('#[^a-zA-Z0-9,._:]#', '', $critvalue);

This removes everything except a-z, A-Z, 0-9, and the puncation characters.

mkrause