简体   繁体   中英

PHP preg_replace if number is bigger then 4 digits in phone number

I have made function to replace the number in string, but it replaces all numbers, I want to make it work if number in string is above 4 digits,

function remove_details($string) {
        $patterns = array();
        $patterns[0] = '/([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/';
        $patterns[1] = '/([0-9]+[\- ]?[0-9]+)/';
        $replacements = array();
        $replacements[0] = '*****';
        $replacements[1] = '*****';
        $descf = preg_replace($patterns, $replacements, $string);
            return $descf;
    }

Here all digits are removed are replaced by * in string, i want to replace if digits in string is more then 4, if digits are less then 4 then keep it, So other numbers won't replaced except the phone numbers.

Here is a short script which handles numbers as you describe:

$string = "random text 123454";
$pattern = "/\d{5,}/";
$descf = preg_replace($pattern, "*****", $string);
echo $descf;

Note that it only replaces numbers consisting of four or more digits in the input string with five stars. I have not checked your email regex logic, and that could have problems too.

No need for regex.
You can use substr, strlen and str_pad to do the same.
Generally regex uses more memory and performance to the same if it's a simple task like this.

$phone = 123456789;

Echo substr($phone, 0,4) . Str_pad("", strlen($phone)-4,"*");
// 1234*****

https://3v4l.org/CPJ52

function remove_details($string) {
        $patterns = array();
        $patterns[0] = '/([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/';
        $patterns[1] = '/([0-9]+[\- ]?[0-9]+)/';
        $replacements = array();
        if(strlen($string)>4)
        {
            $replacements[0] = '*****';
            $replacements[1] = '*****';
            $descf = preg_replace($patterns, $replacements, $string);
        }
        $descf = preg_replace($patterns, $replacements, $string);

            echo $descf;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM