简体   繁体   English

PHP preg_replace(如果数字大于电话号码的4位数字)

[英]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, 我已经制作了替换字符串中的数字的函数,但是它替换了所有数字,如果字符串中的数字大于4位,我想使其工作,

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. 在这里,所有的数字都将被替换为字符串中的*,如果字符串中的数字大于4,我想替换,如果数字小于4,则保留它,因此除了电话号码之外,其他数字将不会被替换。

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. 您可以使用substr,strlen和str_pad进行相同的操作。
Generally regex uses more memory and performance to the same if it's a simple task like this. 通常,如果这样的简单任务,则regex会使用更多的内存和更高的性能。

$phone = 123456789;

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

https://3v4l.org/CPJ52 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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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