开发者

PHP - Removing <?php ?> tags from a string

What's the best way to remove these tags from a string, to prepare it for being passed to eval() ?

for eg. the string can be something like this:

开发者_如何学Go
<?php
  echo 'hello world';
  ?>
  Hello Again
  <?php

  echo 'Bye';
?>

Obviously str_replace won't work because the two php tags in the middle need to be there (the the 1st and the last need to be removed)


Usually, you wouldn't want to pass a function to eval. If you're wishing to just remove the tags, string_replace would do the job just fine, however you might be better off using a regex.

preg_replace(array('/<(\?|\%)\=?(php)?/', '/(\%|\?)>/'), array('',''), $str);

This covers old-asp tags, php short-tags, php echo tags, and normal php tags.


Sounds like a bad idea, but if you want the start and end ones removed you could do

$removedPhpWrap = preg_replace('/^<\?php(.*)(\?>)?$/s', '$1', $phpCode);

This should do it (not tested).

Please tell me also why you want to do it, I'm 95% sure there is a better way.


You could do:

eval("?> $string_to_be_evald <?");

which would close the implicit tags and make everything work.


There's no need to use regex; PHP provides functions for removing characters from the beginning or end of a string. ltrim removes characters from the beginning of the string, rtrim from the end of the string, and trim from both ends.

$code = trim ( $code );
$code = ltrim( $code, '<?php' );
$code = rtrim( $code, '?>' );

The first trim() removes any leading or trailing spaces that are present in the siting. If we omitted this and there was whitespace outside of the PHP tags in the string, then the ltrim and rtrim commands would fail to remove the PHP tags.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜