skeletonne
skeletonne

Reputation: 83

Using preg_replace()?

I'm trying to understand the function preg_replace(), but it looks rather cryptic to me. From looking at the documentation on the function here. I understand that it consists of three things - the subject, the pattern for matching, and what to replace it with.

I'm currently trying to 'sanitize' numerical input by replacing anything that isn't a number. So far I know I would need to allow the numbers 0-9, but remove anything that isn't a number and replace it with: "".

Instead of escaping every character I need to, is there some way to simply not allow any other character than the numbers 0-9? Also if anyone could shed light on how the 'pattern for matching' part works...

Upvotes: 1

Views: 271

Answers (3)

nans
nans

Reputation: 16

is_numeric(); isn't resolve your problem ?

Upvotes: 0

Edward
Edward

Reputation: 1883

preg_replace() is easier than you think:

$p = "/[A-Z a-z]/";
$r = "";
$s = "12345t7890";

echo preg_replace($p, $r, $s);

Will output "123457890" - note no '6'

Upvotes: 1

Adam Franco
Adam Franco

Reputation: 85768

If you want to sanitize a string to replace anything that isn't a number, you would write a regular expression that matches characters not in list.

The pattern [0-9] would match all numerals. Placing a caret (^) at the beginning of the set matches everything that isn't in the set: [^0-9]

$result = preg_replace('/[^0-9]/', '', $input);

Note that this will also filter out periods/decimal points and other mathematical marks. You could include periods/decimal points (allowing floats) by making the period allowed:

$result = preg_replace('/[^0-9.]/', '', $input);

Note that the period (.) is the wildcard character in regular expressions. It doesn't need to be escaped in a bracket expression, but it would elsewhere in the pattern.

Upvotes: 2

Related Questions