如何将php字符串拆分为多个部分

时间:2017-10-31 13:42:55

标签: php

如何分割这个字符串" #now我的时间#Cairo travel#here"成为像那样的阵列

Array ( [0] => #now [1] => my time [2] => #Cairo [3] => travel [4] => #here )

4 个答案:

答案 0 :(得分:0)

<?php

$string='#now my time #Cairo travel #here';
$string=explode(' ',$string);

$result=array($string[0],$string[1].' '.$string[2],$string[3],$string[4],$string[5]);
print_r($result);


Array ( [0] => #now [1] => my time [2] => #Cairo [3] => travel [4] => #here )

答案 1 :(得分:0)

function extractHashes($string) {
  $return = [];
  $r = 0;
  $parts = explode(' ', $string);

  // Helper function return bool if string starts with hash.
  $swh = function ($s) {
    return (strpos($s, '#') === 0);
  };

  for ($p = 0; $p < count($parts); $p++) {
    // Add word or append word to return array.
    if (!isset($return[$r])) {
      $return[$r] = $parts[$p];
    } else {
      $return[$r] .= ' ' . $parts[$p];
    }

    // Increment index if current word or next word starts with hash.
    if ($swh($parts[$p]) || ($p + 1 < count($parts) && $swh($parts[$p + 1]))) {
      $r += 1;
    }
  }

  return $return;
}

你的例子:

$string1 = "#now my time #Cairo travel #here";
print_r( extractHashes($string1) );

输出:

Array
(
    [0] => #now
    [1] => my time
    [2] => #Cairo
    [3] => travel
    [4] => #here
)

另一个例子:

$string2 = "here is #another #string for testing #function works";
print_r( extractHashes($string2) );

输出:

Array
(
    [0] => here is
    [1] => #another
    [2] => #string
    [3] => for testing
    [4] => #function
    [5] => works
)

答案 2 :(得分:0)

在处理变量分隔符时,正则表达式是明智的选择。

var_export(preg_match_all('/#\S+| \K[^#]+\b/','#now my time #Cairo travel #here',$out)?$out[0]:'fail');

这将匹配单个主题标签字和非散列字符串,同时省略其间的空格。

模式演示:https://regex101.com/r/CtnriL/1/

Php演示:https://3v4l.org/CMW77

输出:

array (
  0 => '#now',
  1 => 'my time',
  2 => '#Cairo',
  3 => 'travel',
  4 => '#here',
)

这是另一种使用更简单模式但需要额外函数调用的方法:

var_export(array_map('trim',preg_split('/(#\S+)/','#now my time #Cairo travel #here',null,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY)));

Php演示:https://3v4l.org/d47Tg

答案 3 :(得分:-1)

here

$array = explode(" ", $yourString)