简体   繁体   中英

Remove numbers if greater than X - PHP

I am removing numbers from $name , as follows:

$name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);

Is it possible to remove numbers only if there are more than X numbers , example: joe123456 (six characters) and not if: joe123 or 1joe1234?

You can use preg_replace to remove all the digits from the name, and if the length of the new name is 6 or more less than the old name, replace the old name:

$names = array('joe123456',
               'joe123',
               '1joe1234',
               '123joe456');

foreach ($names as $name) {
    $new_name = preg_replace('/\d/', '', $name);
    if (strlen($new_name) <= strlen($name) - 6) {
        $name = $new_name;
    }
    echo "$name\n";
}

Output:

joe
joe123
1joe1234
joe

Demo on 3v4l.org

I think thats it:

preg_match_all('!\d+!', $namewithoutnumber, $matches);
$numbers = implode('', $matches[0]);

if( strlen($numbers) > 5 ) {
  $name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);
}

Another option:

<?php

$names = array('joe123456',
               'joe123',
               '1joe1234',
               '123joe456',
               '1234567joe12345');

$new_names = [];

foreach ($names as $name) {
    if (preg_match("/\d{6}+/", $name)) {
        $new_names[] = preg_replace('/\d/', '', $name);
    } else {
        $new_names[] = $name;
    }
}

var_dump($new_names);

Yields:

array(5) {
  [0]=>
  string(3) "joe"
  [1]=>
  string(6) "joe123"
  [2]=>
  string(8) "1joe1234"
  [3]=>
  string(9) "123joe456"
  [4]=>
  string(3) "joe"
}

Absolutely; just run it through the strlen() function:

if (strlen($namewithoutnumber) > 5) {
  $name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);
}

您可以为此使用preg_replace

$name = preg_replace('/[0-9]{6,}/', '', $name_with_too_long_numbers);

No Preg match solution:

<?php function searchAndReplace($array, $string, $max_search)
{
    $count = 0;
    foreach ($array as $arr) {
        $count += substr_count($string, $arr);
        if ($count >= $max_search) return str_replace($array,'',$string);
    }
    return $string;
}
function removeNumbers($string)
{   
    $array = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
    return searchAndReplace($array, $string, 6);
}
echo removeNumbers('joe123456'); //joe
echo removeNumbers('joe123'); //joe123
echo removeNumbers('1joe1234'); //1joe1234

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