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



我有这样的句子

  @abc sdf @def wer rty  @ghi xyz

我希望在一个带有钥匙和价值对的数组中像Bellow一样并忽略 @之前的多个空间。我的要求是将下一个立即 @(上面句子中的Ex:ABC)作为数组键,而在 @ and key之前将其作为值(例如:ex:ex:sdf和上述句子中的rty)

>
 array(
       [abc]=>sdf
       [def]=>wer rty
       [ghi]=>xyz
      )

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

获得了很多
 array(
       [0]=>abc
       [1]=>def
       [2]=>ghi
      ) 

这是我现有的代码

  $sentence = "@abc sdf @def wer rty  @ghi xyz"
  if (preg_match_all('/(?<!w)@(w+)/', $sentence, $matches)){
        $splitted = $matches[1];
        print_r($splitted);
        exit;
    }

您可以简单地扩展正则延伸以捕获@words和任何后续字符串

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

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

一个变体是将任何后续字符串与@不包括([^@]+)的任何后续字符串匹配 - 而不仅仅是寻找要遵循的单词/空格。尽管可能需要稍后修剪。

这或多或少是一个非常简化的php拆分字符串的案例

做到这一点的一种方法是使用 .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);

最新更新