我有一個字符串,其中包含花括號中的變量,我想用值替換它們。正則表達式不按預期工作 - PHP preg_match_all
$text = 'Hi My Name is ##{Name}## and I am ##{Adjective}##';
preg_match_all('/{([^#]+)}/i', $text, $matches);
foreach ($matches[1] as $key => $value) {
$text = str_replace('{' . $value . '}', 'SomeValue', $text);
}
print_r($matches[1]);
print_r(str_replace('##', '', $text));
輸出
Array ([0] => Name [1] => Adjective)
Hi My Name is SomeValue and I am SomeValue
但我不能處理字符串例如deifferent變化。
1. $text = 'Hi My Name is ##{Name}{Adjective}##'
2. $text = 'Hi My Name is ##{Name}and I am{Adjective}##'
3. $text = 'Hi My Name is ##{Name}, {Adjective}##'
4. $text = 'Hi My Name is ##{Name} {Adjective}##'
我希望類似的結果陣列的輸出,這樣的值可以被替換
Array ([0] => Name [1] => Adjective)
注:我能保證「##」將始終存在,在開始和結束的大括號,但不一定在大括號之間在示例字符串中點1,2,3,4以上。
爲什麼不用你想要的值替換{Name}和{Adjective}? –
你嘗試過'/ {([^#] +?)}/i'嗎? – Biffen
嘗試preg_match_all(「/ {[a-zA-Z] *} /」,$ input_lines,$ output_array) –