Here is an example of text taken from database and displayed on the page:
Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam,开发者_开发问答 quis nostrud exercitation ullamco laboris etc....
What to do to make the text below to looks like
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
I'm trying to remove all unnecessary white spaces and new lines. I have tested with trim() end str_replace, but I did not get the result that I want.
Might this question help? Remove multiple whitespaces
From the top rated answer written by codaddict:
$ro = preg_replace('/\s+/', ' ',$row['message']);
You are using \s\s+ which means whitespace(space, tab or newline) followed by one or more whitespace. Which effectively means replace two or more whitespace with a single space. What you want is replace one or more whitespace with single whitespace, so you can use the pattern \s\s* or \s+ (recommended)
This will remove all the newlines within your string:
$str = preg_replace('/\s+/', ' ', $str);
Try:
$str = preg_replace('/\s+/', ' ', $str);
http://php.net/manual/en/function.preg-replace.php
<?php
$str = 'foo o';
$str = preg_replace('/\s\s+/', ' ', $str);
// This will be 'foo o' now
echo $str;
?>
Or you can chop string with explode by CRLF, and then trim.
Using trim
and preg_replace
:
$string = trim( preg_replace( '/[\s\s \s]+/', ' ', $string ) );
Try something like this:
$string = 'Lorem ipsum... etc';
$string = preg_replace('/\s+/',' ',$string);
Use $str = preg_replace("/\s\s+/", " ", $str); for spaces
$your_string = str_replace("\r\n\r\n"," ",$your_string); for new lines.
精彩评论