-1

I have text data like this:

                Learn More

        Hide [x]








                            Colors



                    Fetching Colors description...




            Show more topics







                            Art exhibitions



                    Fetching Art exhibitions description...








                            Abstract art



                    Fetching Abstract art description...








                            Representational art



                    Fetching Representational art description...

I'd like to be able to remove all the carriage returns, so it becomes like this:

Learn More Hide [x] Colors Fetching Colors description... Show more topics

How do I do this in PHP? Note that the strings might be UTF-8 string, and we need to take into account various kinds of tab, carriage return and white space characters. (I am thinking along the lines of a tokeniser algorithm used in a compiler, where multiple carriage return and white space characters are taken care of.)

forgodsakehold
  • 870
  • 10
  • 26
  • possibly duplicate of https://stackoverflow.com/questions/6394416/replace-excess-whitespaces-and-line-breaks-with-php and https://stackoverflow.com/questions/6360566/replace-multiple-newline-tab-space – Hiren Aug 29 '18 at 18:26

2 Answers2

5

You can try this with a preg_replace:

http://php.net/manual/en/function.preg-replace.php

$data = preg_replace('/[\s\t\n]{2,}/', ' ', $data);

You can learn more about regular expressions where: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

You can test them live here: https://www.phpliveregex.com/

Pedro Caseiro
  • 485
  • 2
  • 11
2

Try like this with preg_replace() to replace multiple spaces to single space instead of removing tabs(\t), spaces(\s), carriage return(\r) or line feed(\n)

echo preg_replace('/\s+/', ' ', $your_input_string_with_multi_space_goes);

DEMO: https://3v4l.org/XMoVr

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103