2011-05-06 79 views
0

我真的需要preg_replace的帮助。请看下图:Preg替换问题(PHP)

<html>[sourcecode language='php']<?php echo "hello world"; ?>[/sourcecode]</html> 

我只希望它显示的PHP标签和剥离出来休息,所以我会得到以下结果:

<?php echo "hello world"; ?> 

请帮助。我曾尝试以下方法:

$update = get_the_content(); 

$patterns = array(); 
$patterns[0] = '/<html>/'; 
$patterns[1] = '/</html>/'; 
$patterns[2] = '/[sourcecode language]/'; 
$patterns[3] = '/[/sourcecode]/'; 
$replacements = array(); 
$replacements[0] = ''; 
$replacements[1] = ''; 
$replacements[2] = ''; 
$replacements[3] = ''; 

echo preg_replace($patterns, $replacements, $update); 

但它不起作用。我的问题也是语言可能并不总是PHP。

回答

1

您需要使用/作为分隔符和[]当逃脱字符一样/因为他们在使用正则表达式:

$update = get_the_content(); 

$patterns = array(); 
$patterns[0] = '/<html>/'; 
$patterns[1] = '/<\/html>/'; 
$patterns[2] = '/\[sourcecode language\]/'; 
$patterns[3] = '/\[\/sourcecode\]/'; 
$replacements = array(); 
$replacements[0] = ''; 
$replacements[1] = ''; 
$replacements[2] = ''; 
$replacements[3] = ''; 

echo preg_replace($patterns, $replacements, $update); 
0

让您远离方括号。在正则表达式中,[]是表示字符类的标签,并且该模式与括号内的任何一个字符相匹配。

0

何尝不是一种不同的方法:

得到所有PHP的标签和内容

$src = get_the_content(); 
$matches = array(); 
preg_match_all('/(<\?php(?:.*)\?>)/i',$src,$matches); 
echo implode("\n",$matches); 

或获取块[源代码]的所有内容

$src = get_the_content(); 
$matches = array(); 
preg_match_all('/\[sourcecode[^\]]*\](.*)\[\/sourcecode\]/i',$src,$matches); 
echo implode("\n",$matches);