【问题标题】:Splitting a string in multiple values based on string or alphabetic letters?根据字符串或字母将字符串拆分为多个值?
【发布时间】:2014-11-17 08:48:30
【问题描述】:

我希望我能解释我想要实现的目标: 在 PHP 中,我从远程网站接收内容,我想处理这些数据。 我现在有 +- 300 个这样的字符串:

$string=abcdefg123abcdefg    

我想把这个字符串分成三部分:

  • 第一部分:第一个字母字符串 (abcdefg)
  • 第二部分:数字字符串 (123)
  • 第三部分:第二个字母字符串 (abcdefg)

我尝试了一些使用explode函数,但我只能将字符串分成两部分。

【问题讨论】:

标签: php string explode numeric alphabetic


【解决方案1】:

您可以在一系列数字上使用 preg_split() 并捕获分隔符:

$parts = preg_split('/(\d+)/', 'abc123def', 2, PREG_SPLIT_DELIM_CAPTURE);
// $parts := ['abc', '123', 'def']

【讨论】:

    【解决方案2】:
    preg_match("/([a-zA-Z]*)([0-9]*)([a-zA-Z]*)/", $string, $output_array);
    print_r($output_array)
    

    【讨论】:

      【解决方案3】:

      这应该适合你:

      (首先我得到字符串的数字来爆炸字符串!然后我将数字附加到数组中)

      <?php
      
          $string = "abcdefg123abcdefg";
      
          preg_match('!\d+!', $string, $match);   
          $split = explode(implode("",$match), $string);
          $split[2] = $split[1];
          $split[1] = implode("",$match);
      
          print_r($split);
      
      ?>
      

      输出:

      Array
      (
          [0] => abcdefg
          [1] => 123
          [2] => abcdefg
      )
      

      【讨论】:

        【解决方案4】:

        解决方案:

        这将起作用:

        $string = 'abcdefg123abcde';
        preg_match_all('/([0-9]+|[a-zA-Z]+)/',$string,$matches);
        
        print_r( $matches[0] );
        

        输出:

        Array ( [0] => abcdefg [1] => 123 [2] => abcde )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-14
          • 2016-08-09
          • 1970-01-01
          • 2013-10-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多