2012-03-03 7 views
0

に失敗し、preg_replace_callbackに失敗しますが、どのような正確に同じテキストが正常に動作します次のようになります。"%\[if @$username\](.*?)\[/if\]%"

を混乱さ何、私はpreg_quoteとパターンを使用しているということです二重引用符で囲まれています。

$パターンは、(エラー)を失敗しない%\[if @username\](.*?)\[/if\]% を生産するが、あなたはpropably可変スコープの問題を抱えている%\[if @username\](.*?)\[/if\]%作品にうまく

public function output() { 
if (!file_exists($this->file)) { 
    return "Error loading template file ($this->file).<br />"; 
} 
$output = file_get_contents($this->file); 

foreach ($this->values as $key => $value) { 
    $tagToReplace = "[@$key]"; 
    $output = str_replace($tagToReplace, $value, $output); 
    $regex_key = preg_quote($key); 
    $pattern = "%\[if @$regex_key\](.*?)\[/if\]%"; // produces: %\[if @username\](.*?)\[/if\]% 
    $output = preg_replace_callback($pattern, array($this, 'if_replace'), $output); 
} 

return $output; 
} 

public function if_replace($matches) { 

    $matches[0] = preg_replace("%\[if @username\]%", "", $matches[0]); 
    $matches[0] = preg_replace("%\[/if]%", "", $matches[0]); 
    return $matches[0]; 
} 
+0

どのように失敗するのですか?エラーメッセージは何ですか? –

+0

'preg_quote'に区切り文字を伝える必要があります。また、パーサーを書くことが理にかなっている正規表現を使って作業していると思います。 – Wrikken

+0

@Shiplu - エラーメッセージは表示されませんが、何も置き換えられません。 – jsuissa

答えて

0

を書きます。 phpが変数名そのものを挿入するのではなく、phpは変数を知らない。あなたは、コールバックメソッドで$ユーザ名変数を使用しているとして、あなたは$パターンだったやり方を変える)(

0

をif_replaceする

global $username; 

を追加することによって、それが世界的な最初の宣言とメソッドにインポートする必要がある場合があります

OLD:

$pattern = "%\[if @$regex_key\](.*?)\[/if\]%"; 

NEW:

コードに構築は、以下の問題を解決しているようです
$pattern = '%\[if @'.$regex_key.'\](.*?)\[/if\]%'; 
関連する問題