2016-09-14 10 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)); 

OUTPUT

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) 

NOTE交換することができるように、私はアレー出力で同様の結果を望む:私は「##」を常に開始と終了時に存在することを保証することができていますが中括弧の中では必ずしもそうではない上の例の文字列の1,2,3,4を指します。

+0

{名前}と{形容詞}を必要な値に置き換えてください。 –

+1

あなたは '/ {([^#] +?)}/i'を試したことがありますか? – Biffen

+0

preg_match_all( "/ {[a-zA-Z] *)/"、$ input_lines、$ output_arrayを試してください) –

答えて

2

私は、これは「someValueの」と全体{Name}{Adjective}を交換しながら、あなたは$found配列の一致を記録できるようになる。この

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

ようなパターン/\{(.+?)}/とコールバックでpreg_replace_callbackを使用してお勧めします。あなたの質問に基づいて

$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が "Name"、 "Adjective"などの部分を配列に取り込もうと思っています。 – Phil

+0

@Philそれは、私はちょうど置換を行う余分なステップを行っただけです。 –

関連する問題