嗨,我正试图用php preg_match解析一个子字符串。
字符串输入如下:
25k8cp1gl6-Mein Herze im Blut, BWV 199: Recitative: Ich Wunden_SVD1329578_14691639_unified :CPN_trans:这里我想提取Mein Herze im Blut, BWV 199: Recitative: Ich Wunden
25k8cp1gl6-La Puesta Del Sol_SVD1133599_12537702_unified :CPN_trans:这里我想提取La Puesta Del Sol
La Puesta Del Sol_SVD1133599_12537702_unified :CPN_trans:这里我想提取La Puesta Del Sol
25k8cp1gl6-La Puesta Del Sol_MNA1133599_12537702_unified :CPN_trans:这里我想提取La Puesta Del Sol
25k8cp1gl6-La Puesta Del Sol_IMC1133599_12537702_unified :CPN_trans:这里我想提取La Puesta Del Sol
因此,基本上,我想在_SVD或_MNA和_IMC之前提取字符串,不包括字符串25k8cp1gl6-的第一部分。
提前谢谢
发布于 2014-05-07 14:43:24
这是表达给您的:
(?<=25k8cp1gl6-).*?(?=_(?:SVD|MNA|IMC))解释:
(?<=...)是前瞻性的语法,这意味着我们从查找(但不包括在我们的匹配中) "25k8cp1gl6-“开始。然后,我们懒惰地将整个字符串与.*?匹配。最后,(?=...)是一种前瞻性语法。我们寻找"_“后面的"SVD”、"MNA“或"IMC”(在非捕获组|中用(?:...)分隔)。
PHP:
$strings = array(
'25k8cp1gl6-Mein Herze im Blut, BWV 199: Recitative: Ich Wunden_SVD1329578_14691639_unified :CPN_trans:',
'25k8cp1gl6-La Puesta Del Sol_SVD1133599_12537702_unified :CPN_trans:',
'25k8cp1gl6-La Puesta Del Sol_MNA1133599_12537702_unified :CPN_trans:',
'25k8cp1gl6-La Puesta Del Sol_IMC1133599_12537702_unified :CPN_trans:',
);
foreach($strings as $string) {
if(preg_match('/(?<=25k8cp1gl6-).*?(?=_(?:SVD|MNA|IMC))/', $string, $matches)) {
$substring = reset($matches);
var_dump($substring);
}
}另一个使用preg_replace()的选项是在这里降级。
^\w+-(.*?)_(?:SVD|MNA|IMC).*Explanation:
这个字符串匹配整个字符串,但是捕获了我们想要保留的部分,这样我们就可以在替换时引用它。还请注意,我是从^\w+-而不是25k8cp1gl6-开始的。这几乎只是查找任意数量的“单词字符”([A-Za-z0-9_]),后面跟着字符串开头的连字符。如果它需要"25k8cp1gl6-",您可以替换它;我只想展示另一个选项。
PHP:
$strings = array(
'25k8cp1gl6-Mein Herze im Blut, BWV 199: Recitative: Ich Wunden_SVD1329578_14691639_unified :CPN_trans:',
'25k8cp1gl6-La Puesta Del Sol_SVD1133599_12537702_unified :CPN_trans:',
'25k8cp1gl6-La Puesta Del Sol_MNA1133599_12537702_unified :CPN_trans:',
'25k8cp1gl6-La Puesta Del Sol_IMC1133599_12537702_unified :CPN_trans:',
);
foreach($strings as $string) {
$substring = preg_replace('/^\w+-(.*?)_(?:SVD|MNA|IMC).*/', '$1', $string);
var_dump($substring);
}https://stackoverflow.com/questions/23520759
复制相似问题