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 HONGKONG2 . 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
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 2The 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With