提问人:Mike 提问时间:5/7/2014 更新时间:6/26/2020 访问量:11634
PHP / Regex:从字符串中提取字符串
PHP / Regex: extract string from string
问:
我刚刚开始使用PHP,希望这里有人可以帮助我。
我正在尝试从另一个字符串 (“”) 中提取一个字符串 (“”),其中我的字符串总是以“ ”开头,如果主字符串在 myCountry 之后包含更多国家/地区,则以分号 () 结尾,或者如果主字符串之后不包含更多国家/地区,则没有任何内容。myRegion
mainString
myCountry:
;
显示主字符串不同选项的示例:
- myCountry: region1, region2
- myCountry:region1、region2、region3;other国家: region1
- other国家: region1;我的国家/地区:region1;other国家/地区: region1, region2
我想提取的始终是粗体部分。
我在想类似以下内容,但这看起来还不对:
$myRegions = strstr($mainString, $myCountry);
$myRegions = str_replace($myCountry . ": ", "", $myRegions);
$myRegions = substr($myRegions, 0, strpos($myRegions, ";"));
非常感谢您对此的任何帮助,迈克。
答:
12赞
wachme
5/7/2014
#1
使用正则表达式:
preg_match('/myCountry\:\s*([^\;]+)/', $mainString, $out);
$myRegion = $out[1];
评论
0赞
Mike
5/7/2014
谢谢你!一个问题:如果 myCountry 之后会有更多的国家/地区,这只会一直持续到 myCountry 后面的第一个分号(这是我需要的)吗?
1赞
wachme
5/7/2014
是的。它只是从第一个到第一个myCountry:
;
0赞
Mike
5/7/2014
太棒了 - 非常感谢。确认它效果很好,甚至比预期的还要快。
5赞
Andresch Serj
5/7/2014
#2
由于从评论中可以看出您对非正则表达式解决方案感兴趣,并且您是初学者并且对学习感兴趣,因此这是使用 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);
}
只是一个非常简单的例子。
评论
1赞
Sunchock
6/23/2020
我在简单示例的链接上遇到了 502 错误,它已经死了?
1赞
Andresch Serj
6/24/2020
@Sunchock eval.in 似乎已关闭/关闭。我在另一个平台上添加了指向相同代码的新链接。供将来参考:您也可以复制第一个代码块和最后一个代码块,然后自己尝试一下。
1赞
Sunchock
6/24/2020
谢谢,我建议为您的数组示例使用 eddit,因为它有点令人困惑。数组有 3 个条目,但您只写入了 2 个条目。它们与您的第一句话匹配,但与带有 explode 的代码部分不匹配。
0赞
Andresch Serj
6/25/2020
@Sunchock 我没有看到你的编辑,但我想我修复了它?
1赞
Sunchock
6/25/2020
我没有看到更改 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” } 因为你的数组与你的第一句话匹配,但与你的示例不匹配
评论
str_replace
preg_replace