PHP/Regex:从字符串中提取字符串

Mik*_*ike 0 php regex substr strstr str-replace

我刚开始使用PHP,希望有人可以帮助我.

我试图myRegion从另一个字符串(" mainString")中提取一个字符串(" "),其中我的字符串始终以" myCountry:" 开头,;如果主字符串在myCountry之后包含更多国家,则以分号()结尾,如果主字符串不包含任何内容之后不再包含更多国家/地区.

显示主字符串的不同选项的示例:

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

我想要提取的内容始终是粗体部分.

我在考虑类似下面的内容,但这看起来还不对:

$myRegions = strstr($mainString, $myCountry);                   
$myRegions = str_replace($myCountry . ": ", "", $myRegions);
$myRegions = substr($myRegions, 0, strpos($myRegions, ";"));
Run Code Online (Sandbox Code Playgroud)

迈克,非常感谢您提供任何帮助.

小智 8

使用正则表达式:

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


And*_*erj 5

由于从评论看来您对非正则表达式解决方案感兴趣,并且由于您是初学者并且对学习感兴趣,因此这是另一种可能的方法,使用explode. (希望这不是没有必要的)。

首先,认识到您有由 分隔的定义,;因为它是:

myCountry: region1, region2, region3 ; otherCountry: region1

因此,使用explode,您可以生成定义的数组:

$string = 'otherCountry: region1; myCountry: region1; otherCountry: region2, region3';
$definitions = explode (';', $string);
Run Code Online (Sandbox Code Playgroud)

给你

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

您现在可以迭代该数组(使用foreach)并使用 分解它:,然后使用 分解该数组的第二个结果,。通过这种方式,您可以建立一个关联数组,其中包含您的国家/地区及其各自的区域。

$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);
}
Run Code Online (Sandbox Code Playgroud)

只是一个非常简单的例子