PHP / Regex: 从字符串中删除字符串

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

我正在尝试提取字符串 /"
myRegion

"/ 来自另一个字符串 /"
mainString

"/, 我的字符串总是从哪里开始 "
myCountry:

" 并以分号结尾 /
;

/, 如果主线包含更多国家 myCountry OR 如果主线不包含更多国家之后,没有东西。

示例以显示主线的各种选项

:

myCountry:

区域1,Region2.

myCountry:

Region1,Region2,Region3

; otherCountry: 区域1

otherCountry: region1; myCountry:

region1

; otherCountry: region1, region2

我想要提取的是始终以粗体突出显示。

我想到了像下一个这样的事情,但它仍然看起来不正确

:


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


提前感谢您的任何帮助,迈克。
已邀请:

冰洋

赞同来自:

使用正则表达式:


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

小明明

赞同来自:

由于评论似乎对以外的决定感兴趣 regex, 由于您是新的学习,这里是另一种可能的方法
http://www.php.net/manual/en/function.explode.php
.
/

我希望这不适合

/.

首先,承认您有定义分开
;

, 因为它是:


myCountry: region1, region2, region3


;


otherCountry: region1


因此 , 使用
http://www.php.net/manual/en/function.explode.php
, 您可以生成一系列定义:


$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"
}


现在你可以通过这个数组。 /使用
http://www.php.net/manual/en/c ... h.php
/ 并用它吹着
:

, 然后炸毁了这个的第二个结果
,

.
因此,您可以创建包含各自区域的联想阵列。


$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/;
}


就是这样
http://sandbox.onlinephpfuncti ... 1720e
对于游戏。

要回复问题请先登录注册