2014-05-07 94 views
0

我刚开始使用PHP,希望这里有人能帮助我。PHP/Regex:从字符串中提取字符串

我想从另一个字符串中提取的字符串(“myRegion‘)(’mainString‘)在我的字符串始终以’myCountry:”开头和结尾用分号(;)如果主字符串包含myCountry后,越来越多的国家或者如果主字符串后面没有包含更多国家,则没有任何内容。

实施例,以显示主串不同的选项:

  • myCountry:REGION1,区域2
  • myCountry:REGION1,区域2,区域3; otherCountry:region1
  • otherCountry:region1; myCountry:region1; otherCountry:region1,region2

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

我想的是类似以下内容,但这看起来不正确还:

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

提前为任何帮助,迈克非常感谢。

+0

仅供参考:您的示例中没有使用正则表达式。'str_replace'不使用REGEX - 'preg_replace'确实是http://www.php.net/manual/en/function.preg-replace.php –

+0

我知道,只是想提一下,如果这是一个更好的选择。 – Mike

回答

8

使用正则表达式:

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

感谢!一个问题:如果在myCountry之后会有更多的国家会这么做,直到myCountry之后的第一个分号(这是我需要的)? – Mike

+1

是的。它适用于您发布的每个示例字符串 – wachme

+1

是的。它只需要从'myCountry:'到第一个';' – wachme

3

因为从它看起来像你有兴趣在非正则表达式的解决方案,并因为你是一个初学者,兴趣学习,这是一个使用explode另一种可能的方法的意见。 (希望这不是不要求)。

首先,要认识到你必须;分隔的定义,因为它是:

myCountry: region1, region2, region3;otherCountry: region1

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

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

给你

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

您现在可以遍历数组(使用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玩。

+1

非常感谢,这也非常有帮助! – Mike