2012-05-09 53 views
8

我有一個字符串,它是這樣的全部替換內側的圖案

{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }} 

我希望它成爲

{{ some text ### other text ### and some other text }} @ this should not be replaced {{ but this should: ### }} 

我猜的例子是直線前進夠了,我不知道我可以更好地解釋我想用文字來達到的目標。

我嘗試了幾種不同的方法,但都沒有工作。

回答

8

這可以用正則表達式回調到一個簡單的字符串替換來實現性能或適合您的需求。

匿名函數將允許你參數化的替代品:

$find = '@'; 
$replace = '###'; 
$output = preg_replace_callback(
    '/{{.+?}}/', 
    function($match) use ($find, $replace) { 
     return str_replace($find, $replace, $match[0]); 
    }, 
    $input 
); 

文檔:http://php.net/manual/en/function.preg-replace-callback.php

2

你可以用2個正則表達式來完成。第一個選擇{{}}之間的所有文本,第二個替換爲@###。使用正則表達式2可以做這樣的:

$str = preg_replace_callback('/first regex/', function($match) { 
    return preg_replace('/second regex/', '###', $match[1]); 
}); 

現在您可以在第一和第二正則表達式,嘗試自己,如果你不明白這一點,要求它在這個問題上。

function replaceInsideBraces($match) { 
    return str_replace('@', '###', $match[0]); 
} 

$input = '{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }}'; 
$output = preg_replace_callback('/{{.+?}}/', 'replaceInsideBraces', $input); 
var_dump($output); 

我選擇了一個簡單的非貪婪正則表達式來找到你的大括號,但你可以選擇改變這個爲:

2

另一種方法是使用正則表達式(\{\{[^}]+?)@([^}]+?\}\})。你需要在它幾次跑匹配內部{{括號}}多個@ S:

<?php 

$string = '{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }}'; 
$replacement = '#'; 
$pattern = '/(\{\{[^}]+?)@([^}]+?\}\})/'; 

while (preg_match($pattern, $string)) { 
    $string = preg_replace($pattern, "$1$replacement$2", $string); 
} 

echo $string; 

,輸出:

{{一些文本###其它文本###和一些其他的文字}} @這個應該是 不能被替換{{但這應該是:###}}