Abs
Abs

Reputation: 57916

Migrate from ereg_replace to preg_replace

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

Upvotes: 1

Views: 1153

Answers (2)

mkrause
mkrause

Reputation: 1399

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.

Upvotes: 3

cletus
cletus

Reputation: 625077

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.

Upvotes: 2

Related Questions