简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM