Preg_replace()?

I have the string (619) 435-8120 and want to convert it to 6194358120
Cutting out spaces, parenthesis, and -, is this correct?

$var=(619) 435-8120

preg_replace('/\s+\(\)-/','',$var);

You should use with this syntax:

<?php
        $var='(619) 435-8120';

      echo  $var=preg_replace("/[\s+\(\)-]/", '',$var);
        ?>

The output is this:6194358120

With this syntax :

<?php
        $var='(619) 435-8120';

      echo  $var=preg_replace("/[\s+\(\)-]/",' ',$var);
        ?>

you’ll take this:619 435 8120

You don’t need a regexp for this.

$var = str_replace([' ','(',')','-'], '', $var);

while to clean up the numbers better use explicit filtering

$var=preg_replace("/[^0-9]/", '',$var);
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.