PHP - 删除 来自字符串的标签
从字符串中删除这些标签以准备将其传递给 eval() 的最佳方法是什么?
例如。字符串可以是这样的:
<?php
echo 'hello world';
?>
Hello Again
<?php
echo 'Bye';
?>
显然 str_replace 不起作用,因为中间的两个 php 标签需要在那里(第一个和最后一个需要删除)
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:
<?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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通常,您不想将函数传递给 eval。
如果您只想删除标签, string_replace 就可以很好地完成这项工作,但是您最好使用正则表达式。
preg_replace(array('/<(\?|\%)\=?(php)?/', '/(\%|\?)>/'), array('','' ), $str);
这涵盖了旧的 asp 标签、php 短标签、php echo 标签和普通 php 标签。
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.
听起来是个坏主意,但如果你想删除开始和结束的部分,你可以
这样做应该这样做(未经测试)。
请告诉我你为什么要这样做,我 95% 确信有更好的方法。
Sounds like a bad idea, but if you want the start and end ones removed you could do
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:
which would close the implicit tags and make everything work.
不需要使用正则表达式; PHP 提供了从字符串开头或结尾删除字符的函数。
ltrim
从字符串的开头删除字符,< code>rtrim 从字符串的 end 开始,并且修剪
从两端。第一个
trim()
删除站点中存在的任何前导或尾随空格。如果我们忽略了这一点,并且字符串中 PHP 标记外部有空格,那么ltrim
和rtrim
命令将无法删除 PHP标签。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, andtrim
from both ends.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 theltrim
andrtrim
commands would fail to remove the PHP tags.