sammyukavi
sammyukavi

Reputation: 1511

Preg Replace Numerals

I'm a newbie to preg_replace function. I have the following expression that I want to replace the numbers 0-9 with # in a string. It's returning the same string with no changes, where could I have gone wrong? I tried google but still cannot find the solution. Thanks.

$phonenumber = "0720123456";
    $format = trim(preg_replace("/[^0-9]/", "#", $phonenumber));

Upvotes: 0

Views: 58

Answers (2)

anubhava
anubhava

Reputation: 785186

[^0-9] will match anything except a digit.

You need to use [0-9] or shortcut \d:

$format = trim(preg_replace("/\d/", "#", $phonenumber));

Upvotes: 4

BlitZ
BlitZ

Reputation: 12168

Just use /[0-9]/ as your regular expression.

Your expression /[^0-9]/ means to replace any character, but not (by ^) numerals.

Example:

<?php
header('Content-Type: text/plain; charset=utf-8');

$phonenumber = "0720123456";
$format = trim(preg_replace("/[0-9]/", "#", $phonenumber));

echo $format;
?>

Result:

##########

Upvotes: 3

Related Questions