PHP Preg_Replace for Spaces and Linebreaks



Hey Guys,

On my localized server the following code works perfectly to remove all spaces and linebreaks and insert a comma.

[php]$page_data[‘output’] = preg_replace(’/\s\s+/’, ‘,’, $this->input->post(‘input’));[/php]

  • Note I am using CodeIgnitor for this development version.

It correctly parses a list like this:


But when running on DreamHost the function doesn’t work at all. Any thoughts or assistance would be greatly appreciated.


I’m not sure how your regex, which matches spaces, could replace newlines with commas.

[php]preg_replace(’/[\s\n]+/’, ‘,’, $this->input->post(‘input’));[/php]


There’s a nice little cheat sheet here if you’re new (or old even!) to regular expressions.


Thank you for the suggestion. I need to account for multiple spaces also (we all know the users don’t think like coders).

I ended up just telling it to identify any multiple spaces.
[php]$page_data[‘output’] = preg_replace("/\s+/", ‘,’, $this->input->post(‘input’));[/php]

Apparently PHP also recognizes line breaks as a space or multiple space because it worked, kinda strange.

sXi, didn’t see your post as I was posting. Consider it saved and printed. I have a good handle on regular expressions but cheat sheets are always nice.


Well, what you had originally works on 2 or more spaces only. Depending on the framework you are using, and/or whether your output is in a div or textarea, your regex only works by chance. If your output is in a div or otherwise, then the newlines are still there, but they are not shown in rendered html. You’ll need to look at the actual html or even better, dump the contents of both input and output with a die(); afterwards to see what’s really going on. Best would be to set up a test: