【问题标题】:PHP explode on second instance of a delimiterPHP 在分隔符的第二个实例上爆炸
【发布时间】:2017-08-02 04:59:36
【问题描述】:

我正在尝试使用 PHP 分解字符串,但只有在分解它之前检测到分隔符的第二个实例时,对于我的情况,我想在检测到第二个空格后分​​解它。

我的字符串

Apple Green Yellow Four Seven Gray

我的愿望输出

Apple Green
Yellow Four
Seven Gray

我的初始代码

$string = 'Apple Green Yellow Four Seven Gray';
$new = explode(' ',$string);

如何使用explode 或PHP 的任何分离方法来实现这一点?提前致谢!

【问题讨论】:

    标签: php explode


    【解决方案1】:

    好问题 - 可以通过多种方式完成。我想出了这个 1 -

     $data='Apple Green Yellow Blue';
    
    
    $split = array_map(
        function($value) {
            return implode(' ', $value);
        },
        array_chunk(explode(' ', $data), 2)
    );
    
    var_dump($split);
    

    【讨论】:

    • 在我的情况下它只返回Array ( [0] => Apple Green [1] => Yellow Four Seven Gray ) 不知何故错过了Seven Gray
    • 好的@KaoriYui ..我做错了,请查看我更新的答案..它将完美运行
    • 好的,我把分隔符改成空格,把var_dump改成print_r,这个最简单,谢谢!
    • 哦再次...对不起队友..我将其更新为空格分隔符。
    【解决方案2】:

    你也可以用这个:

    $string = 'Apple Green Yellow Four Seven Gray';
    $lastPos = 0;
    $flag = 0;
    while (($lastPos = strpos($string, " ", $lastPos))!== false) {  
        if(($flag%2) == 1)
        {
            $string[$lastPos] = "@";
        }
        $positions[] = $lastPos;
        $lastPos = $lastPos + strlen(" ");
        $flag++;
    }
    $new = explode('@',$string);
    print_r($new);
    exit;
    

    【讨论】:

      【解决方案3】:

      您可以为此使用正则表达式。

      $founds = array();
      $text='Apple Green Yellow Four Seven Gray';
      preg_match('/^([^ ]+ +[^ ]+) +(.*)$/', $text, $founds);
      

      也参考下面answer

      【讨论】:

      • 我的输出是Array ( [0] => Apple Green Yellow Four Seven Gray [1] => Apple Green [2] => Yellow Four Seven Gray ) ,它错过了爆炸时的Seven Gray
      • 查看我在答案中引用的链接。它会帮助你
      【解决方案4】:

      使用explode 您无法获得所需的输出。您必须使用 preg_match_all 来查找所有值。 这是一个例子:

      $matches = array();
      preg_match_all('/([A-Za-z0-9\.]+(?: [A-Za-z0-9\.]+)?)/',
             'Apple Green Yellow Four Seven Gray',$matches);
      
      print_r($matches);
      

      如果您有任何问题,请告诉我。

      【讨论】:

        猜你喜欢
        • 2011-06-24
        • 1970-01-01
        • 2013-06-08
        • 1970-01-01
        • 1970-01-01
        • 2020-12-13
        • 2019-06-05
        • 1970-01-01
        • 2011-02-21
        相关资源
        最近更新 更多