Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove white space from the start of every new line of a string

I have a string that comes in in the following format (notice the random number of spaces in between each word and at the beginning of each line):

 1 . BritishAirways 15FEB LONDON HONGKONG

    2 . CathayPacific 01MAR HONGKONG SHANGHAI

  3 . Qantas 12MAR SINGAPORE SYDNEY

I want the output to be

1 . BritishAirways 15FEB LONDON HONGKONG
2 . CathayPacific 01MAR HONGKONG SHANGHAI 
3 . Qantas 12MAR SINGAPORE SYDNEY   

I've got the below code

$flightinfo = preg_replace('/\h+/', ' ', $flightinfo);
$flightinfo = trim($flightinfo);

$flightinfo = str_replace("\r\n\r\n","\r\n",$flightinfo);/* checks and removes double line breaks if they're there.

However this gives the below, which is nearly correct however it was white space at the beginning of lines 2 and 3

1 . BritishAirways 15FEB LONDON HONGKONG
  2 . CathayPacific 01MAR HONGKONG SHANGHAI 
 3 . Qantas 12MAR SINGAPORE SYDNEY   

Anyone know how I can remove the white space at the beginning of lines 2 and 3

like image 810
WillMaddicott Avatar asked Sep 12 '25 03:09

WillMaddicott


1 Answers

You may use a single regex replacement to achieve what you need:

$flightinfo = preg_replace('~^\h+|\h+$|(\R){2,}|(\s){2,}~m', '$1$2', $flightinfo);

See the regex demo.

Details

  • ^\h+ - any 1 or more horizontal whitespaces at the start of a line (^ matches a line start due to the m modifier)
  • | - or
  • \h+$ - any 1 or more horizontal whitespaces at the end of a line ($ matches a line end due to the m modifier)
  • | - or
  • (\R){2,} - 2 or more line break sequences capturing the last one into Group 1
  • | - or
  • (\s){2,} - 2 or more whitespaces capturing the last one into Group 2

The replacement is the replacement backreferences to Group 1 and 2.

See the PHP demo:

$re = '/^\h+|\h+$|(\R){2,}|(\s){2,}/m';
$flightinfo = ' 1 . BritishAirways 15FEB LONDON HONGKONG


     2 . CathayPacific  01MAR     HONGKONG   SHANGHAI



  3 . Qantas   12MAR SINGAPORE SYDNEY';
$flightinfo = preg_replace($re, '$1$2', $flightinfo);
echo $flightinfo;

Output:

1 . BritishAirways 15FEB LONDON HONGKONG
2 . CathayPacific 01MAR HONGKONG SHANGHAI
3 . Qantas 12MAR SINGAPORE SYDNEY
like image 187
Wiktor Stribiżew Avatar answered Sep 14 '25 16:09

Wiktor Stribiżew