2012-12-28 47 views
0

我有一個包含在方backets,我想識別,提取,並用別的東西代替幾個關鍵字串:的preg_match,str_replace函數和所有爵士樂

例如:

'You will win [winnings] or [slice].'

我想要識別廣場內的所有術語,將這些術語替換爲某些值。

所以應該結束這樣的:

'You will win 100 or 95%.'

任何想法?

+0

可能dublicate:http://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets – Peon

回答

1
$replacements = array(
    'winnings' => '100' 
    , 'slice' => '95%' 
    , 'foobar' => 'Sean Bright' 
); 

$subject = '[foobar], You will win [winnings] or [slice]!'; 

$result = preg_replace_callback(
    '/\[([^\]]+)\]/', 
    function ($x) use ($replacements) { 
     if (array_key_exists($x[1], $replacements)) 
      return $replacements[$x[1]]; 
     return ''; 
    }, 
    $subject); 

echo $result; 

注意,這將徹底崩潰,如果你有不平衡的括號(即[[foo]

對於PHP版本低於5.3:

$replacements = array(
    'winnings' => '100' 
    , 'slice' => '95%' 
    , 'foobar' => 'Sean Bright' 
); 

function do_replacement($x) 
{ 
    global $replacements; 

    if (array_key_exists($x[1], $replacements)) 
     return $replacements[$x[1]]; 
    return ''; 
} 

$subject = '[foobar], You will win [winnings] or [slice]!'; 

$result = preg_replace_callback(
    '/\[([^\]]+)\]/', 
    'do_replacement', 
    $subject); 

echo $result; 
+0

喜歡這個樣子,但我發現了一個錯誤代碼? – ojsglobal

+0

你有什麼錯誤?我已經在本地進行了測試,並且工作正常 –

+0

解析錯誤:語法錯誤,意想不到的T_FUNCTION在12行/home/slimming/public_html/aardvark.php 即: 函數($ x)使用($ replacements){ – ojsglobal

3

小菜一碟

$search = array('[winnings]', '[slice]'); 
$replace = array(100, '95%'); 

echo str_replace($search, $replace, 'You will win [winnings] or [slice].'); 
0

如果您想使用正則表達式來查找匹配項:

$content = "You will win [winnings] or [slice]."; 
preg_match_all('/\[([a-z]+)\]/i', $content, $matches); 

$content = str_replace($matches[0], array('100', '95%'), $content); 

var_dump($content);