2016-02-05 25 views
0

我有一個字符串。提取關鍵字Word模式

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

我想從字符串中提取所有{$word}。我試圖使用str_replace但它不起作用。

+0

'{$ USER1,$ USER2,$ USER3}'不看起來像一個有效的字符串插值 –

+0

先生,我只需要這些詞作爲數組 – Deepesh

+0

數組('0'=>'{$ USER_NAME}','1'=> {$ USER1,$ USER2,$ USER3}) – Deepesh

回答

1

簡短的解決方案與preg_mach_all功能:

$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

+0

非常感謝您的來信。 – Deepesh

+0

先生,我在reg_exp爲零,無法在此找到好的教程。你能否提出任何建議。當然是 – Deepesh

+0

。至於PHP:我會建議從官方指南開始:http://php.net/manual/en/reference.pcre.pattern.syntax.php。 至於Javascript:試試這個教程:http://www.regular-expressions.info。用表達式鞏固你的知識。搜索和下載正則表格:它們非常方便 – RomanPerekhrest

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

輸出將是:

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

非常感謝您的致謝 – Deepesh