
[英]PHP: echo words within string where start and end are always the same
[英]Php echo where both " and ' are used in the string?
一个字符串看起来像这样:
<form id="unban" method="post" action="unban.php?uid=<? echo $uID; ?>">
<input type="hidden" name="name" value="" />
<a onclick="document.getElementById('unban').submit();">UnBan</a>
</form>
我需要用大量其他变量来回显它(因为有 if 语句所以我不能把它放在 php 标签之外)但是我找不到一种方法将它存储在变量中并在回显中使用它。 我的回声看起来像:
echo "<tr><td>" . $row['username'] . "</td><td>" . $banBool . "</td><td>". $status ."</td><td>" . $row['full_name'] . "</td></tr>";
其中$status
将是上面的形式,具体取决于 if 语句。
有没有办法将它作为一个字符串保存并仍然这样做?
此外,只是为了澄清 javascript 语法需要“目标”并且不允许“目标”
您可以在 PHP if 块中编写正常的 HTML - 只需关闭并重新打开 PHP 标签:
<?php
if($something == $somethingelse) {
?>
<form id="unban" method="post" action="unban.php?uid=<?php echo $uID; ?>">
...
</form>
<?php
}
如果你真的需要将它保存在一个字符串中,只需确保通过在每个引号之前添加一个反斜杠来转义任何类型的引号来保存字符串:
$status = '<form id="unban" method="post" action="unban.php?uid='.$uID.'">
<input type="hidden" name="name" value="" />
<a onclick="document.getElementById(\'unban\').submit();">UnBan</a>
</form>
(另请注意,您不能在变量内执行回显 - 只需将字符串与变量连接起来)
每当您 output 更复杂的东西或需要两种类型的引号时,您应该使用HEREDOC
字符串:
echo <<<HTML
<tr><td> $row[username] </td><td>
$banBool </td><td> $status </td><td> $row[full_name]
</td></tr>
HTML;
请注意如何避免在此处引用数组键(表现得像双引号字符串)。
如果您需要为 Javascript 用法准备一个字符串,那么另外json_encode()
可能是明智的。
我喜欢在字符串中回显变量的最干净的方式是这样的:
echo "This is a string with a {$variables["variable"]} in it. If I have to use another double-quote within this string I'll escape it with a \"backslash\".";
我通常完全避免混合使用单引号和双引号(必要时除外,例如您的 JavaScript function,以帮助减少混淆。
你的 HTML 可以这样写:
echo "<form id=\"unban\" method=\"post\" action=\"unban.php?uid={$uID}\">
<input type=\"hidden\" name=\"name\" value=\"\" />
<a onclick=\"document.getElementById('unban').submit();\">UnBan</a>
</form>\n";
回显的结果字符串将具有自然字符并具有适当的空白格式。
使用反斜杠转义引号:\'
为什么不直接转义引号呢?
echo "\"", '\''; // "'
如果那不可能,请查看 PHP 的heredoc 和 nowdoc语法。 go 的第三种方法是在 IF 语句中间关闭 PHP 块,output 直接关闭 HTML。
哦,你也可以使用输出缓冲:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.