如果大于 X,则删除数字 - PHP

我正在从 中删除数字,如下所示:$name

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

是否可以仅在数字超过 X 时删除数字,例如:joe123456(六个字符),而不能删除 if:joe123 或 1joe1234?


神不在的星期二
浏览 115回答 5
5回答

阿晨1998

您可以使用 删除名称中的所有数字,如果新名称的长度小于或大于旧名称,请替换旧名称:preg_replace$names = array('joe123456',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'joe123',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'1joe1234',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'123joe456');foreach ($names as $name) {&nbsp; &nbsp; $new_name = preg_replace('/\d/', '', $name);&nbsp; &nbsp; if (strlen($new_name) <= strlen($name) - 6) {&nbsp; &nbsp; &nbsp; &nbsp; $name = $new_name;&nbsp; &nbsp; }&nbsp; &nbsp; echo "$name\n";}输出:joejoe1231joe1234joe3v4l.org 演示

aluckdog

另一种选择:<?php$names = array('joe123456',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'joe123',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'1joe1234',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'123joe456',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'1234567joe12345');$new_names = [];foreach ($names as $name) {&nbsp; &nbsp; if (preg_match("/\d{6}+/", $name)) {&nbsp; &nbsp; &nbsp; &nbsp; $new_names[] = preg_replace('/\d/', '', $name);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; $new_names[] = $name;&nbsp; &nbsp; }}var_dump($new_names);收益 率:array(5) {&nbsp; [0]=>&nbsp; string(3) "joe"&nbsp; [1]=>&nbsp; string(6) "joe123"&nbsp; [2]=>&nbsp; string(8) "1joe1234"&nbsp; [3]=>&nbsp; string(9) "123joe456"&nbsp; [4]=>&nbsp; string(3) "joe"}

犯罪嫌疑人X

您可以使用preg_replace来实现此目的。$name&nbsp;=&nbsp;preg_replace('/[0-9]{6,}/',&nbsp;'',&nbsp;$name_with_too_long_numbers);

ibeautiful

我想就是这样:preg_match_all('!\d+!', $namewithoutnumber, $matches);$numbers = implode('', $matches[0]);if( strlen($numbers) > 5 ) {&nbsp; $name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);}

皈依舞

当然可以;只需通过&nbsp;strlen()&nbsp;函数运行它:if&nbsp;(strlen($namewithoutnumber)&nbsp;>&nbsp;5)&nbsp;{ &nbsp;&nbsp;$name&nbsp;=&nbsp;str_replace&nbsp;(array&nbsp;('0',&nbsp;'1',&nbsp;'2',&nbsp;'3',&nbsp;'4',&nbsp;'5',&nbsp;'6',&nbsp;'7',&nbsp;'8',&nbsp;'9'),&nbsp;''&nbsp;,&nbsp;$namewithoutnumber); }
打开App,查看更多内容
随时随地看视频慕课网APP