PHP: How to prevent unwanted line breaks

强颜欢笑 提交于 2019-12-13 15:00:12

问题


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?


回答1:


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));

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




回答2:


My guess is your variables are to blame. You might try cleaning them up with trim: http://us2.php.net/trim.




回答3:


The line breaks show up because of multi-byte encoding, I believe. Try:

$newstring =  mb_substr($string_w_line_break,[start],[length],'UTF-8');

That worked for me when strange line breaks showed up after parsing html.



来源:https://stackoverflow.com/questions/4251983/php-how-to-prevent-unwanted-line-breaks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!