开发者

PHP: How to prevent unwanted line breaks

I'm using PHP to create some basic HTML. The tags are always the same, but the actual links/titles correspond to PHP variable开发者_开发百科s:

$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?


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜