2016-09-14 56 views
2

我有一個字符串,其中包含花括號中的變量,我想用值替換它們。正則表達式不按預期工作 - 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以上。

+0

爲什麼不用你想要的值替換{Name}和{Adjective}? –

+1

你嘗試過'/ {([^#] +?)}/i'嗎? – Biffen

+0

嘗試preg_match_all(「/ {[a-zA-Z] *} /」,$ input_lines,$ output_array) –

回答

2

我推薦使用preg_replace_callback與圖案/\{(.+?)}/和回調這樣

$callback = function($matches) use (&$found) { 
    $found[] = $matches[1]; 
    return 'SomeValue'; 
}; 

這將讓你記錄$found陣列中的比賽,而更換整個{Name}{Adjective}與「someValue中」。這裏

$found = []; 
$newTxt = str_replace('##', '', 
    preg_replace_callback('/\{(.+?)}/', $callback, $txt)); 

演示〜根據您的問題https://eval.in/641827

1

,你可以先提取所有那些## ##之間的東西,對其進行分析,然後更換之後。

$text1 = 'Hi My Name is ##{Name}{Adjective}##'; 
$text2 = 'Hi My Name is ##{Name}and I am{Adjective}##'; 
$text3 = 'Hi My Name is ##{Name}, {Adjective}##'; 
$text4 = 'Hi My Name is ##{Name} {Adjective}##'; 

$the_text = $text2; 

#get the stuff that's between ## ## 
preg_match_all("/##.*?##/", $the_text, $matches); 

foreach ($matches[0] as $match) 
{ 
    # you will have to change this a bit as you have name and adjectives 
    # but what this does is replace all the '{}' with 'somevalue' 
    $replace_this = preg_replace("/\{.*?\}/", "somevalue", $match); 
    # replaces the original matched part with the replaced part (into the original text) 
    $the_text = str_replace($match, $replace_this, $the_text); 
} 
echo $the_text . "<br>"; 
+0

我認爲OP還想要捕獲數組中的「名稱」,「形容詞」等部分 – Phil

+0

@Phil它是這樣做的,我只是做了替換的額外步驟。 –

相關問題