PHP String Concatenate问题

时间:2013-02-10 15:03:39

标签: php

以下PHP字符串的输出不正确。它最后显示了额外的(“>”。请帮助我做错了什么?

$part2 = HTMLentities('<input type="hidden" name="custom" value="<?php print($_SESSION["muser"]."-".$_SESSION["mpass"]);?>">');
print $part2;

谢谢,KRA

3 个答案:

答案 0 :(得分:3)

如果您已经处于PHP模式,则应该使用字符串连接而不是<?php ?>语法;这个例子拆分了html创建和转义部分。

$html = '<input type="hidden" name="custom" value="' . htmlspecialchars($_SESSION["muser"] . "-" . $_SESSION["mpass"]) . '">';

$part2 = htmlentities($html);
print $part2;

答案 1 :(得分:0)

这是因为还有一个&gt;在末尾。 试试这个:

$part2 = HTMLentities('<input type="hidden" name="custom" value="<?php print($_SESSION["muser"]."-".$_SESSION["mpass"]);?>"');
print $part2;

答案 2 :(得分:0)

我认为这更像是你在寻找的东西:

$part = '<input type="hidden" name="custom" value="' . htmlentities($_SESSION['user'] . '-' . $_SESSION['mpass']) . '" />';

您的示例中有很多糟糕的PHP语法。

  • 我们使用<?php标签从HTML中转义为PHP。当你有一个PHP文件时,你可以想到的一个方法是你真的有一个HTML文档 - 但你可以添加<?php标签来编写PHP代码。在你的例子中你试图从PHP中打印HTML,这可能会变得非常复杂。您已经在PHP块中,因此您不需要使用开始<?php标记。
  • 连接字符串以存储在变量中时,您不需要使用print函数。 print函数用于将文本写入屏幕。您可以使用我编写的示例中的变量名称来组合字符串。
  • htmlentities用于将字符串中的任何HTML呈现为文本。我们使用htmlentities来保护未知(用户输入的)数据不会修改我们的HTML。如上所述,在$ _SESSION变量上使用htmlentities是一个好主意,以确保它们不会使用无效的HTML破坏我们的input标记。在整个字符串上使用它只会打印您的HTML,就好像它是原始文本一样。

以下是从PHP块外部编写它的方法:

<?php
    // initial PHP code
?>

<input type="hidden" name="custom" value="<?php echo htmlentities($_SESSION['user'] . '-' . $_SESSION['mpass']) ?>" />

<?php
    // continue PHP code
?>