PHP / Regex: extract string from string

Mike picture Mike · May 7, 2014 · Viewed 9.5k times · Source

I just started using PHP and hope someone here can help me with this.

I am trying to extract a string ("myRegion") from another string ("mainString") where my string always starts with "myCountry: " and ends with a semicolon (;) if the main string contains more countries after myCountry OR without anything if the main string does not contain more countries after it.

Examples to show different options for main string:

  • myCountry: region1, region2
  • myCountry: region1, region2, region3; otherCountry: region1
  • otherCountry: region1; myCountry: region1; otherCountry: region1, region2

What I want to extract is always the part in bold.

I was thinking of something like the following but this doesn't look right yet:

$myRegions = strstr($mainString, $myCountry);                   
$myRegions = str_replace($myCountry . ": ", "", $myRegions);
$myRegions = substr($myRegions, 0, strpos($myRegions, ";"));

Many thanks in advance for any help with this, Mike.

Answer

wachme picture wachme · May 7, 2014

Using regular expression:

preg_match('/myCountry\:\s*([^\;]+)/', $mainString, $out);
$myRegion = $out[1];