0

I Have a string data coming from for loop, i want to remove specific characters and special characters from a string.Please find below my data.

["\r\n \r\n 300518<\/departureDate>\r\n\t\t\t\t\t\t\t\t\t
  \r\n\t\t\t\t\t\t\t\t\t \r\n <\/availabilityDetails>\r\n
  \r\n HYD<\/cityAirport>\r\n <\/departureLocationInfo>\r\n
  \r\n DXB<\/cityAirport>\r\n <\/arrivalLocationInfo>\r\n
  <\/availabilityProductInfo>702<\/orderClassesByCabin>
  <\/cabinOption>",44,"AUHOT3116"]

i tried str_replace and trim functions in php but not working.I want out put from this string like below.

300518-departuredate-availabilityDetails-HYD-cityAirport-departureLocationInfo-DXB-
cityAirport-arrivalLocationInfo-availabilityProductInfo-702-
orderClassesByCabin-44-AUHOT3116

simply remove all \,r,n,t from this string. Can any one will help me.I was tried not getting result.Thanks advance..

Daniel Larsson
  • 527
  • 2
  • 6
  • 23
Niru
  • 1
  • 4
  • 5
    Possible duplicate of [Remove excess whitespace from within a string](https://stackoverflow.com/questions/1703320/remove-excess-whitespace-from-within-a-string) – Stephen Lake Nov 11 '18 at 14:27

2 Answers2

1
$cleanString = preg_replace('/\s+/', ' ', $yourString);
Stephen Lake
  • 1,582
  • 2
  • 18
  • 27
0

Please have a look at the code below:

<?php
//the data seems to be actually an array
$array = ["\r\n \r\n 300518<\/departureDate>\r\n\t\t\t\t\t\t\t\t\t \r\n\t\t\t\t\t\t\t\t\t \r\n <\/availabilityDetails>\r\n \r\n HYD<\/cityAirport>\r\n <\/departureLocationInfo>\r\n \r\n DXB<\/cityAirport>\r\n <\/arrivalLocationInfo>\r\n <\/availabilityProductInfo>702<\/orderClassesByCabin><\/cabinOption>",44,"AUHOT3116"];

//should yield
$desired_output = "300518-departuredate-availabilityDetails-HYD-cityAirport-departureLocationInfo-DXB-cityAirport-arrivalLocationInfo-availabilityProductInfo-702-orderClassesByCabin-44-AUHOT3116";

$trim = ["\t","\r","\n","<\/",">"," "]; //characters or substrings you want removed

foreach($array as &$value) {
    $value = str_replace($trim,"-",$value); //removing unwanted characters
    $value = preg_replace('/[- ]{2,}/','-',$value); //removing duplicates
    $value = trim($value,"- "); //removing trailing and ending unwanted characters
}

$replaced_output = implode("-",$array); //converting the initial array to string

echo "<pre>";
var_dump($desired_output,$replaced_output);

https://3v4l.org/3cdqO

Note that the expected string and the processed string are not identical because there was an element called 'cabinOption' that doesn't fit the removing criteria, so it was left as it was.

EDIT: To have the processed string identical with the desired string, just add whatever string you want removed in the $trim array.

https://3v4l.org/uujfC

This may not be the best way to do it, it's just a possible solution for this specific case. You should consider a more generic approach, regular expressions etc.

Dan D.
  • 815
  • 9
  • 16