在 PHP 中连接 HTML 字符串和变量
问题描述:
这种连接HTML字符串和变量的解决方案不方便,因为我们需要中断字符串:
This solution to concatenate HTML string and variable is not convenient because we need to interrupt the string:
$content = '<meta property="foo" url="' . $url . '" name="' . $name . '">';
而这个不方便,因为我们必须通过 \"
转义 "
:
whereas this one is not handy because we have to escape "
by \"
:
$content = "<meta property=\"foo\" url=\"$url\" name=\"$name\">";
您会使用哪些其他解决方案(不需要额外功能)来提高代码可读性?
注意:不是heredoc相关问题的重复,因为我在这里寻找单行解决方案.
Note: not a duplicate of heredoc related questions because here I'm looking for a one-line solution.
答
对原始 HTML 使用单引号,对 PHP 变量使用花括号.像这样;
Use single quotes for raw HTML and curly braces around PHP variables. Like so;
$content = "<meta property='foo' url='{$url}' name='{$name}'>";