Mahantesh
Mahantesh

Reputation: 357

Get the words/sentences after a specific character and put them in array with key and value pairs

I have a sentence like this

  @abc sdf @def wer rty  @ghi xyz

I want this in an array with key and value pairs like bellow and neglect the multiple spaces before @. My requirement is take whatever is there immediate next @(ex:abc in above sentence) as array key and whatever further before @ and key as explained take it as value(ex:sdf and wer rty in above sentence)

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

After lot of search and practice I got this much using preg_match_all()

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

This is my existing code

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

Upvotes: 1

Views: 37

Answers (2)

mario
mario

Reputation: 145482

You can simply expand the regex to capture @words and any followup string thereafter

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

Then simply array_combine $matches[1] and [2] for the associative array.

A variation would be to match any followup strings excluding @ with ([^@]+) - instead of just looking for words/spaces to follow. Albeit that might require trimming later on.

This is more or less a very simplified case of PHP Split Delimited String into Key/Value Pairs (Associative Array)

Upvotes: 1

Goma
Goma

Reputation: 1981

One way for doing this is using .explode(), then just cut the portion of key and value from each element. I used .strstr() and .str_replace() for example

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

Upvotes: 0

Related Questions