【问题标题】:PHP / Regex: extract string from stringPHP / Regex:从字符串中提取字符串
【发布时间】:2014-06-24 07:10:51
【问题描述】:

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

我正在尝试从另一个字符串 ("mainString") 中提取一个字符串 ("myRegion"),其中我的字符串始终以 "myCountry:" 开头并以分号 (;) 结尾,如果主字符串在 myCountry 之后包含更多国家,或者如果主字符串之后不包含更多国家,则没有任何内容。

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

  • myCountry: region1, region2
  • myCountry: region1, region2, region3;其他国家:地区1
  • 其他国家:地区1;我的国家:region1;其他国家:地区1,地区2

我要提取的始终是粗体部分。

我正在考虑类似以下的内容,但这看起来还不正确:

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

非常感谢您在此提供的任何帮助,迈克。

【问题讨论】:

  • 仅供参考:您的示例中没有使用正则表达式。 str_replace 不使用正则表达式 - preg_replace 使用 php.net/manual/en/function.preg-replace.php
  • 我知道,只是想提一下,以防它在这里是一个更好的选择。

标签: php regex str-replace substr strstr


【解决方案1】:

使用正则表达式:

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

【讨论】:

  • 谢谢!一个问题:如果在 myCountry 之后会有更多的国家,这会一直持续到 myCountry 之后的第一个分号(这是我需要的)?
  • 是的。它只需要从myCountry: 到第一个; 的所有内容
  • 太棒了 - 非常感谢。确认效果很好,甚至比预期的还要快。
【解决方案2】:

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

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

myCountry: region1, region2, region3 ; otherCountry: region1

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

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

给你

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

您现在可以迭代这个数组(使用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);
}

只是一个非常适合玩的simple example

【讨论】:

  • 我在简单示例的链接上出现 502 错误,它已经死了?
  • @Sunchock eval.in 似乎已关闭/关闭。我在另一个平台上添加了指向相同代码的新链接。供以后参考:您也可以只复制第一个代码块和最后一个代码块并自己尝试。
  • 谢谢,我为您的数组示例建议了一个 eddit,因为它有点令人困惑。该数组有 3 个条目,但您只写了 2 个条目。它们与您的第一句话匹配,但与您的代码部分不匹配。
  • @Sunchock 我没有看到你的编辑,但我想我修好了?
  • 我没有看到更改 array(3) { [0]=> string(19) " myCountry: region1, region2, region3" [1]=> string(31) " otherCountry: region1 " } 将变为 array(3) { [0]=> string(19) "otherCountry: region1" [1]=> string(31) " myCountry: region1" [2]=> string(31) " otherCountry: region2 , region3" } 因为您的数组与您的第一句话匹配,但与您使用爆炸的示例不匹配
猜你喜欢
  • 2023-01-07
  • 2020-06-10
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 2019-03-14
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多