0

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));

2 Answers 2

4

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

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

$format = trim(preg_replace("/\d/", "#", $phonenumber));
Sign up to request clarification or add additional context in comments.

Comments

3

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:

##########

1 Comment

It makes sense to explain what was wrong with the original regex. You want to teach him fishing not feed with fish, don't you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.