代码之家  ›  专栏  ›  技术社区  ›  KaoriYui

PHP在定界符的第二个实例上爆炸

  •  1
  • KaoriYui  · 技术社区  · 7 年前

    我的字符串

    Apple Green Yellow Four Seven Gray

    Apple Green
    Yellow Four
    Seven Gray
    

    我的初始代码

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

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

    4 回复  |  直到 7 年前
        1
  •  4
  •   Farsay    7 年前

    很好的问题-可以用很多方法来实现。我想出了这个1-

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

    您也可以使用它:

    $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
  •  1
  •   Murtaza Khursheed Hussain    7 年前

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

    answer

        4
  •  1
  •   Bhavin Solanki    7 年前

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

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