Question

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.

Was it helpful?

Solution

Using regular expression:

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

OTHER TIPS

Since from the comments it seems like you are interested in non-regex solutions and since you are a beginner and interested in learning, here's another possible approach using explode. (Hope this is not uncalled for).

Firstly, recognise that you have definitions seperated by ; since it is:

myCountry: region1, region2, region3 ; otherCountry: region1

So, using explode, you can generate an array of your definitions:

$string = 'otherCountry: region1; myCountry: region1; otherCountry: region2, region3';
$definitions = explode (';', $string);

giving you

array(3) {
  [0]=>
  string(21) "otherCountry: region1"
  [1]=>
  string(19) " myCountry: region1"
  [2]=>
  string(31) " otherCountry: region2, region3"
}

You could now iterate over this array (using foreach) and explode it using : and then explode the second result of that using ,. This way you could build up an associative array holding your Countries with their respective regions.

$result = array();
foreach ($definitions as $countryDefinition) {
  $parts = explode (':', $countryDefinition); // parting at the :
  $country = trim($parts[0]); // look up trim to understand this
  $regions = explode(',', $parts[1]); // exploding by the , to get the regions array
  if(!array_key_exists($country, $result)) { // check if the country is already defined in $result
    $result[$country] = array();
  }
  $result[$country] = array_merge($result[$country], $regions);
}

Just a very simple example to play with.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top