douzhang8033 2019-06-16 18:00
浏览 133

PHP - 如何使用explode()或preg_split()函数忽略字符串上的数字/数字

I want to make explode or preg_split function to ignore numbers/numeric.

$string = "my name is numbre 9000 900 1";

$dictionary = array("my", "name", "is", "number");

$words = explode(' ',$string);

foreach($words as $wrd):

if(in_Array($wrd, $dictionary)){
  echo $wrd;
}
elseif(in_Array($wrd, $dictionary) == FALSE){
  echo $wrd."->wrong";
}

the output I want should be:

my
name
is
numbre<-wrong
9000
900
1

not:

my
name
is
numbre<-wrong
9000<-wrong
900<-wrong
1<-wrong

any idea how do I do this?

  • 写回答

2条回答 默认 最新

  • douchenzhan3050 2019-06-16 18:07
    关注

    Your original method is just fine, we'd slightly modify that and apply the preg_split. Here, we check first for is_numeric, if TRUE we continue, then we array_search our dictionary, if FALSE we append ->wrong, otherwise we continue.

    Test

    $str = "my name is numbre 9000 900 1 and some other undesired words";
    $dictionary = array("my", "name", "is", "number");
    $arr = preg_split('/\s/', $str);
    
    foreach ($arr as $key => $value) {
        if (is_numeric($value)) {
            continue;
        } elseif (array_search($value, $dictionary) === false) {
            $arr[$key] = $value . "->wrong";
        } else {
            continue;
        }
    }
    
    var_dump($arr);
    

    Output

    array(12) {
      [0]=>
      string(2) "my"
      [1]=>
      string(4) "name"
      [2]=>
      string(2) "is"
      [3]=>
      string(13) "numbre->wrong"
      [4]=>
      string(4) "9000"
      [5]=>
      string(3) "900"
      [6]=>
      string(1) "1"
      [7]=>
      string(10) "and->wrong"
      [8]=>
      string(11) "some->wrong"
      [9]=>
      string(12) "other->wrong"
      [10]=>
      string(16) "undesired->wrong"
      [11]=>
      string(12) "words->wrong"
    }
    

    RegEx Demo

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c