Search code examples
phptrimdouble-quotes

How to remove leading and trailing characters from a string?


I have a crooked data """" { ... } """ I want to polish it out a little bit.

How do I take off " before my open { and also take off the " after my closing } ?


Example

"""
{\n
  "ip": "50.198.81.174",\n
  "hostname": "50-198-81-174-static.hfc.comcastbusiness.net",\n
  "city": "Braintree",\n
  "region": "Massachusetts",\n
  "country": "US",\n
  "loc": "42.2038,-71.0022",\n
  "org": "AS7922 Comcast Cable Communications, Inc.",\n
  "postal": "02184"\n
}
"""

Solution

  • Use trim function in PHP:

    $trimmed = trim('"""" { ... } """', '"');
    echo $trimmed;
    

    OUTPUT:

    { ... }

    You can also use rtrim (removes from right side) and ltrim (removes from left side).