Deepesh
Deepesh

Reputation: 180

Extract keyword that Word Pattern

I have an string.

hi {$USER_NAME} THIS IS THE TEST MSG FOR {$USER1,$USER2,$USER3}

I want to extract all the {$word} from the string. I have tried to use str_replace but its not working.

Upvotes: 0

Views: 57

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Short solution with preg_mach_all function:

$str = 'hi {$USER_NAME} THIS IS THE TEST MSG FOR {$USER1,$USER2,$USER3}';
preg_match_all('/\s*(\{\$[^\{\}]+\})+\s*/iue', $str, $matches);

echo "<pre>";
var_dump($matches[1]);

// the output:
array(2) {
  [0]=>
  string(12) "{$USER_NAME}"
  [1]=>
  string(22) "{$USER1,$USER2,$USER3}"
}

http://php.net/manual/ru/function.preg-match-all.php

Upvotes: 1

Alexander Mikhalchenko
Alexander Mikhalchenko

Reputation: 4565

$string = 'hi {$USER_NAME} THIS IS THE TEST MSG FOR {$USER1,$USER2,$USER3}';
$variableRegexp = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
$repeatedVariableRegex = $variableRegexp . '(?:,\s*?\$' . $variableRegexp . ')*';
preg_match_all('/\{\$' . $repeatedVariableRegex . '\}/', $string, $matches);
var_dump($matches);

The output would be:

array(1) {
  [0] =>
  array(2) {
    [0] =>
    string(12) "{$USER_NAME}"
    [1] =>
    string(22) "{$USER1,$USER2,$USER3}"
  }
}

Upvotes: 1

Related Questions