PHP字符串不允许<和>人物 [英] PHP string doesn't allow < and > characters

查看:76
本文介绍了PHP字符串不允许<和>人物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有一个字符串,如下例所示:

I have a string in my code as per the following example:

<?php
$find = '<tag';
$string = 'blah blah <tag=something>';
?>

很简单,但是当我尝试回显字符串时,就不喜欢<或>个字符.回声全部是:

Simple enough, but when I try to echo the strings, it's not liking the < or > characters. All that get's echo'ed is:

等等

所以,基本上我猜我需要转义这些字符才能使它们在PHP中工作,但我不确定具体如何.我正在将其用于模板系统,因此可以在html文件中使用以下文件来包含文件:

So, basically i'm guessing I need to escape these characters to get them to work in PHP but im not sure exactly how. I'm using this for a templating system, so in the html file a file can be included by using:

<include="filename.html">

所以我不需要显示<和>字符随时显示在屏幕上,我只需要读取文件,查找这些标签的实例并做一些魔术即可.我已经将所有这些部分都工作了,但这只是任何包含大于/小于似乎无法正常运行的运算符的字符串.

So I don't need to show the < and > characters on the screen at any time, I just need to read the file, find the instances of these tags and do some magic. I've got all of that part working but It's just any string that contains more than / less than operators that don't seem to work OK.

有什么想法吗?

推荐答案

使用PHP可以生成HTML标记,因此您必须找到一种区分HTML元素字符(<&>)的方法. HTML中存在特殊的字符序列,称为 HTML实体.这些符号以&"号表示,以某种速记形式并以分号结尾.

With PHP you can generate HTML markup, so you have to find a way to distinguish between HTML element characters ( < & > ). There exist special sequence of characters in HTML that are called HTML entities. Those are described with an ampersand, some sort of shorthand and end with a semi-colon.

以下是一些示例:

&gt;     : > (greater-than)
&lt;     : < (less-than)
&amp;    : & (ampersand)
&raquo;  : » (right angle quote marks)
&eacute; : é (e acute)

几乎所有字符都可以用这样的实体表示,但是很快就会变得乏味.您只需要记住<和>一个,再加上&网址.

Almost all characters can be represented with such entities, but it quickly gets tedious. You only have to remember the < and > ones, plus the & for URLs.

如果您打算显示小于/大于符号,则应该这样重写您的代码.

Your code should be rewritten like this if your intention was to show the less-than / greater-than signs.

<?php
$find = '&lt;tag';
$string = 'blah blah &lt;tag=something&gt;';
?>

如其他答案所述,您可以使用函数htmlspecialchars()转换变量中的字符(例如,来自用户输入).

As mentioned in other answers, you can use the function htmlspecialchars() to convert characters in a variable (e.g. from user input).

<?php echo htmlspecialchars($string); ?>

将显示blah blah <tag=something>以便在Web浏览器中查看.否则,例如,如果您在命令行上使用PHP,则无需使用此功能.

will display blah blah <tag=something> for viewing in a web browser. Else, if you were using PHP on the command line for example, you would not need to use this function.

这篇关于PHP字符串不允许&lt;和&gt;人物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆