【问题标题】:Split string based on different "keywords" in PHP在 PHP 中根据不同的“关键字”拆分字符串
【发布时间】:2016-11-04 11:03:53
【问题描述】:

我在 PHP 中有一个字符串:

$haystack = "[:something 1]Here is something 1 content[:something 2]here is something else[:something completely different]Here is the completely different content"

而且它可以永远持续下去。

所以,我需要将它们拆分成一个关联数组:

$final_array = [
   'something 1' => 'Here is something 1 content',
   'something 2' => 'here is something else',
   'something completely different' => 'Here is the completely different content'
]

唯一设置的是开头[:,然后是结尾] 关键字可以是带有空格等的整个句子。

如何做到这一点?

【问题讨论】:

  • 显示你的代码,你尝试了什么..
  • 使用正则表达式匹配:查看 PREG_MATCH_ALL()
  • 你试过什么?请发布一些示例数据和代码,并告诉我们什么不适合您。另外,请查看此链接:stackoverflow.com/help/mcve。

标签: php arrays regex


【解决方案1】:

试试这个,使用explode

$str = "Hello world. It's a beautiful day.";
$main_array = explode("[:",$haystack);
foreach($main_array as $val)
{
    $temp_array = explode("]",$val);
    $new_array[$temp_array[0]] =  $temp_array[1];
}
print_r(array_filter($new_array));

DEMO

【讨论】:

    【解决方案2】:

    您需要使用explode 来拆分您的字符串。像这样:

         $haystack = "[:something 1]Here is something 1 content[:something 2]here is something else[:something completely different]Here is the completely different content";
    
        // Explode by the start delimeter to give us 
        // the key=>value pairs as strings
        $temp = explode('[:', $haystack);
        unset($temp[0]); // Unset the first, empty, value
        $results= []; // Create an array to store our results in
    
        foreach ($temp as $t) { // Foreach key=>value line
            $line = explode(']', $t); // Explode by the end delimeter
            $results[$line[0]] = end($line); // Add the results to our results array
        }
    

    【讨论】:

      【解决方案3】:

      怎么样:

      $haystack = "[:something 1]Here is something 1 content[:something 2]here is something else[:something completely different]Here is the completely different content";
      $arr = preg_split('/\[:(.+?)\]/', $haystack, 0, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
      $res = array();
      for($i = 0; $i < count($arr); $i += 2) {
          $res[$arr[$i]] = $arr[$i+1];
      }
      print_r($res);
      

      输出:

      Array
      (
          [something 1] => Here is something 1 content
          [something 2] => here is something else
          [something completely different] => Here is the completely different content
      )
      

      【讨论】:

      • 我喜欢这个除了.+?之外的一切——出于性能原因,我宁愿看到一个否定的字符类。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2018-05-12
      相关资源
      最近更新 更多