开发者

Preg replace issue (PHP)

开发者 https://www.devze.com 2023-03-03 17:19 出处:网络
I really need help with preg_replace. See below: <html>[sourcecode language=\'php\']<?php echo \"hello world\"; ?>[/sourcecode]</html>

I really need help with preg_replace. See below:

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

I only want it to display the PHP tags and strip the rest out, so I would get the following result:

<?php echo "hello world"; ?>

Please help. I have tried the following:

开发者_如何学JAVA$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);

But it doesn't work. My issue also is the language might not always be PHP.


You need to escape chars like / when using / as a delimiter and [] as they have uses in regex:

$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);


Escape your square-brackets. In regular expressions, [ and ] are the tags that indicate a character class, and the pattern is matching any one of those characters within the brackets.


why not a different approach:

get all php tags and content

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

or get all contents of [sourcecode] blocks

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

精彩评论

暂无评论...
验证码 换一张
取 消