removing spaces and line breaks - php

Busy's picture

He has: 6,151 posts

Joined: May 2001

I'm trying to find away to remove multi spaces from within a string (trim() only does start and end), also a fool proof way of removing adjusting multi line breaks.

example:

This old                             dog

has




fleas.
'for the line breaks I tried doing the old $theoutput = str_replace("\n\n","\n",$theinput); and also \n\r\n\r
I want to allow one \n for sentence and max of two \n's for paragraph, problems arise when there is more than three, unless I place it in a while loop which I'd rather not do if I can help it.

for the spaces tried str_replace(" "," ",$theinput) but it messes up the line breaks - need to display as nl2br on output

Anyone done anything like this before?

He has: 1,380 posts

Joined: Feb 2002

Well....if you're html-ifiying this...it could turn out that your input is:

This&nbsp;old&nbsp;&nbsp;&nbsp;dog<br />
has<br />
<br />
<br />
fleas
'

So in that instance, you would want to search for the HTML components, and not the PHP line break or blank space.

Busy's picture

He has: 6,151 posts

Joined: May 2001

Thanks but I'm not "html-ifiying" it, comes from a form into a database, but need to strip spaces etc before going in, then when displayed am using nl2br()

He has: 1,380 posts

Joined: Feb 2002

well why don't you try doing nl2br() first, and then searching for the 's...see if that works, just to see if your logic is correct.

Busy's picture

He has: 6,151 posts

Joined: May 2001

Thanks but been there done that,

Biggest problem is if there are say six 's, ideally it should be cut down to two str_replace("\n","",$theinput);

I have to do several combinations, , \n, \n\r etc

Something I'm thinking of trying is to strip all double spaces out " " and adding a \n after a full stop. Down side is if the full stop isn't used it wont work as intended Sad also if a measurment is used, ie. 12.5 mm

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.