在PHP字符串中添加换行符

3

我试图在字符串的末尾添加新行,这样我就可以更好地看到新行中的<option>,但是我得到了文本为"\r\n"的字符串,而不是新行。代码有什么问题吗?

foreach ($xml['ROW'] as $ar) {
   $tekstas = $ar['zz'] . ' (' . $ar['xx'] . ')';
   $insert .= '<option value="' . $ar['Adresas'] . '">' . $tekstas .'</option> "\r\n"' ;
}
echo nl2br(htmlentities($insert));
3个回答

3

快了,看看正确的方法如何将新行连接到生成的字符串的其余部分。

foreach ($xml['ROW'] as $ar) {
 $tekstas = $ar['zz'] . ' (' . $ar['xx'] . ')';
 $insert .= '<option value="' . $ar['Adresas'] . '">' . $tekstas   .'</option> ' . PHP_EOL ;
}
echo nl2br(htmlentities($insert));

1
在Windows上使用\r\n,在基于UNIX的系统上使用\n。如果您使用常量PHP_EOL,它将更兼容两者。 - HPierce

2

'引用的字符串不像"引用的字符串那样遵守转义元字符:

echo '\r' - outputs a literal backslash and an 'r'
echo "\r" - outputs a carriage return

' 字符串中支持的唯一转义字符为 \'\\

因此...

'</option> "\r\n"' 
^---open single quote string
                 ^---close single-quote string

当它应该是这样的

'</option> ' . "\r\n"

取而代之。


1
"

"\r\n"应该使用双引号。

"
foreach ($xml['ROW'] as $ar) {
   $tekstas = $ar['zz'] . ' (' . $ar['xx'] . ')';
   $insert .= '<option value="' . $ar['Adresas'] . '">' . $tekstas .'</option>'."\r\n";
}
echo nl2br(htmlentities($insert));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接