PHP:如何防止不必要的换行符 [英] PHP: How to prevent unwanted line breaks

查看:94
本文介绍了PHP:如何防止不必要的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHP来创建一些基本的HTML。标签总是相同的,但实际的链接/标题对应于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);

由此产生的html,既回显(当我查看页面源代码)和简单的txt文件我正在写信,内容如下:

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>

虽然这可行,但这并不是我想要的。看起来PHP每次中断字符串插入变量时都会添加换行符。有没有办法来防止这种行为?

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?

推荐答案

虽然它不会影响你的HTML页面,除非你使用 pre 或 text-wrap:pre ),你应该可以调用 trim()来删除换行符。

Whilst it won't affect your HTML page at all with the line breaks (unless you are using pre or text-wrap: pre), you should be able to call trim() on those variables to remove newlines.

为了弄清楚你的变量在前面还是后面有换行符,试试这个正则表达式

To find out if your variable has a newline at front or back, try this regex

var_dump(preg_match('/^\n|\n$/', $variable));

(我认为您必须使用单引号,这样PHP不会将您的 \\\
转换为字符串中的文字换行符)。

(I think you have to use single quotes so PHP doesn't turn your \n into a literal newline in the string).

这篇关于PHP:如何防止不必要的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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