sysrq
sysrq

Reputation: 135

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?

Upvotes: 0

Views: 273

Answers (6)

c1u31355
c1u31355

Reputation: 448

You could use preg_replace for this.

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

Upvotes: 1

Jacob Mulquin
Jacob Mulquin

Reputation: 3608

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"
}

Upvotes: 1

Ebrahim Mohammed
Ebrahim Mohammed

Reputation: 373

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

Upvotes: 0

Nick
Nick

Reputation: 147206

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

Upvotes: 2

Robin Gillitzer
Robin Gillitzer

Reputation: 1612

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

Upvotes: 1

Obsidian Age
Obsidian Age

Reputation: 42354

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

Upvotes: 0

Related Questions