Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP remove line break or CR LF with no success

I did a function to remove line break with php with no success, i tryed all replace code and i still get these line break, i create a json file and i can't read it from jsonp with jquery because of these line break seem to break it all.

function clean($text)
{
$text = trim( preg_replace( '/\s+/', ' ', $text ) );  
$text = preg_replace("/(\r\n|\n|\r|\t)/i", '', $text);
return $text;
}

When i look at the source, there some line break appening in all href, img and br this is a json_encode output example:

<a
href=\"http:\/\/example.com\/out\/content\/\" title=\"link to content website\">

line break afer a. it's hapenig to img src and br

the only way i can remove these break it with

$text = preg_replace("/\s/i", '', $text);

But you understant that there's no space left in all the string and it's not what we want.

like image 389
Gino Avatar asked Mar 04 '12 19:03

Gino


People also ask

How to remove line breaks in PHP?

The line break can be removed from string by using str_replace() function.

How do you remove a line break in a string?

Remove All Line Breaks from a String We can remove all line breaks by using a regex to match all the line breaks by writing: str = str. replace(/(\r\n|\n|\r)/gm, ""); \r\n is the CRLF line break used by Windows.

How break a string from line in PHP?

The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (\n) in a string.

How do I change all line breaks?

Remove Line Breaks in a Cell Later, if you want to replace all the line breaks with a space character, use a special shortcut — Ctrl + J — in the Find and Replace dialog box.


1 Answers

How about the following

function clean($text)
{
    return trim(preg_replace("/(\s*[\r\n]+\s*|\s+)/", ' ', $text));
}

the first part \s*[\r\n]+\s* will replace any line breaks, it's leading spaces and it's tailing spaces into just one space.

the second part \s+ will shrink spaces into one space.

then trim() removes the leading/tailing space.

like image 160
Jack Ting Avatar answered Sep 27 '22 20:09

Jack Ting