-1

I am pulling location off an API.

The variable $location sometimes contains:

  1. Paris
  2. New York (Manhattan)

Paris is OK.

I only want the city name. So, New York (Manhattan) should be New York.

How do I remove everything after the 1st bracket (and including the 1st bracket) in variable $location?

And will the code that does that affect the content of $location if it only contains 1 word (e.g. Paris)?

Thank you.

Cody Raspien
  • 1,753
  • 5
  • 26
  • 51

2 Answers2

2
$pos = strpos($location, "(");

if ($pos) $location = substr($location, 0, $pos);

What about this?

Jonny 5
  • 12,171
  • 2
  • 25
  • 42
Fappie.
  • 482
  • 6
  • 18
1

You can use a regex like below and use an empty replacement string:

\(.*

Working demo

$re = "/\\(.*/"; 
$str = "Paris New York (Manhattan)\n\nParis is OK. I only want the city name. So, New York (Manhattan) should be New York.\n"; 

$result = preg_replace($re, "", $str);

Check the substitution panel below:

enter image description here

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123