我有一個包含在方backets,我想識別,提取,並用別的東西代替幾個關鍵字串:的preg_match,str_replace函數和所有爵士樂
例如:
'You will win [winnings] or [slice].'
我想要識別廣場內的所有術語,將這些術語替換爲某些值。
所以應該結束這樣的:
'You will win 100 or 95%.'
任何想法?
我有一個包含在方backets,我想識別,提取,並用別的東西代替幾個關鍵字串:的preg_match,str_replace函數和所有爵士樂
例如:
'You will win [winnings] or [slice].'
我想要識別廣場內的所有術語,將這些術語替換爲某些值。
所以應該結束這樣的:
'You will win 100 or 95%.'
任何想法?
$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;
小菜一碟
$search = array('[winnings]', '[slice]');
$replace = array(100, '95%');
echo str_replace($search, $replace, 'You will win [winnings] or [slice].');
如果您想使用正則表達式來查找匹配項:
$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);
可能dublicate:http://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets – Peon