获取特定字符后的单词/句子,并将它们放在包含键和值对的数组中

时间:2017-11-25 04:48:27

标签: php

我有这样的句子

  var sessionInit = session({
  name: 'userCookie',
  secret: '9743-980-270-india',
  resave: true,
  httpOnly: true,
  saveUninitialized: true,
  store: new mongoStore({
    mongooseConnection: mongoose.connection
  }),
  cookie: {
    maxAge: 80 * 80 * 800
  }
});

app.use(sessionInit);

我想在一个包含键和值对的数组中使用它 并忽略@之前的多个空格。 我的要求是把下一个@(例如上面句子中的abc)作为数组键,然后在@和键之前进一步将其视为值(例如:上述句子中的sdf和wer rty)

  @abc sdf @def wer rty  @ghi xyz

经过大量的搜索和练习,我使用preg_match_all()

得到了这么多
 array(
       [abc]=>sdf
       [def]=>wer rty
       [ghi]=>xyz
      )

这是我现有的代码

 array(
       [0]=>abc
       [1]=>def
       [2]=>ghi
      ) 

2 个答案:

答案 0 :(得分:1)

您可以简单地展开正则表达式来捕获@words以及之后的任何后续字符串

preg_match_all('/ (?<!\w)@(\w+) \s+ ((?:\w+\s*)*) /x', $sentence, $matches);
#                        ↑       ↑       ↑
#                       @abc   space   words+spaces

然后简单地array_combine $匹配关联数组的[1]和[2]。

变体将匹配除@([^@]+)之外的任何后续字符串 - 而不仅仅是查找要遵循的字词/空格。虽然可能需要稍后修剪。

这或多或少是PHP Split Delimited String into Key/Value Pairs (Associative Array)

的简化案例

答案 1 :(得分:0)

执行此操作的一种方法是使用.explode(),然后只删除每个元素的键和值部分。我使用了.strstr().str_replace()作为示例

$string = '@abc sdf @def wer rty @ghi xyz';


$array = explode('@',$string); // explode string with '@' delimiter
array_shift($array);           // shift array to remove first element which has no value

$output = [];                  // Output array
foreach ($array as $string) {  // Loop thru each array as string
    $key = strstr($string, ' ', true);  // take the string before first space
    $value = str_replace($key . ' ', "", $string); // removes the string up to first space
    $output[$key] = $value;    // Set output key and value
}

// Print result
print_r($output);