PHP:如何防止不必要的换行
我正在使用 PHP 创建一些基本的 HTML。标签总是相同的,但实际的链接/标题对应于 PHP 变量:
$string = '<p style="..."><a href="'.$html[$i].'"><strong><i>'.$title[$i].'</i></strong></a>
<br>';
echo $string;
fwrite($outfile, $string);
生成的 html,无论是回显(当我查看页面源代码时)还是在我正在写入的简单 txt 文件中,内容如下
<p style="..."><a href="http://www.example.com
"><strong><i>Example Title
</i></strong></a></p>
<br>
:这有效,但这不完全是我想要的。看起来每次我中断字符串以插入变量时 PHP 都会添加换行符。有没有办法阻止这种行为?
I'm using PHP to create some basic HTML. The tags are always the same, but the actual links/titles correspond to PHP variables:
$string = '<p style="..."><a href="'.$html[$i].'"><strong><i>'.$title[$i].'</i></strong></a>
<br>';
echo $string;
fwrite($outfile, $string);
The resultant html, both as echoed (when I view the page source) and in the simple txt file I'm writing to, reads as follows:
<p style="..."><a href="http://www.example.com
"><strong><i>Example Title
</i></strong></a></p>
<br>
While this works, it's not exactly what I want. It looks like PHP is adding a line break every time I interrupt the string to insert a variable. Is there a way to prevent this behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
虽然换行符根本不会影响您的 HTML 页面(除非您使用
pre
或text-wrap: pre
),但您应该能够调用 < code>trim() 在这些变量上删除换行符。要查明您的变量在前面或后面是否有换行符,请尝试此正则表达式
(我认为您必须使用单引号,这样 PHP 就不会将您的
\n
转换为字符串中的文字换行符) 。Whilst it won't affect your HTML page at all with the line breaks (unless you are using
pre
ortext-wrap: pre
), you should be able to calltrim()
on those variables to remove newlines.To find out if your variable has a newline at front or back, try this regex
(I think you have to use single quotes so PHP doesn't turn your
\n
into a literal newline in the string).我的猜测是你的变量是罪魁祸首。您可以尝试使用
trim
清理它们:https://www.php.net/修剪。My guess is your variables are to blame. You might try cleaning them up with
trim
: https://www.php.net/trim.我相信,由于多字节编码而出现换行符。尝试:
当解析 html 后出现奇怪的换行符时,这对我有用。
The line breaks show up because of multi-byte encoding, I believe. Try:
That worked for me when strange line breaks showed up after parsing html.