使用preg_match从字符串中提取两个字符串

问题描述 投票:0回答:2

我正在尝试从字符串中提取两个字符串。字符串的格式如下:

$text = 'First string here(second here)';

秒字符串将始终位于引号内的末尾。我试图有效地提取它们。我试过用这个:preg_match('#\((.*?)\)#', $text, $match)preg_match('/\(([^\)]+)\)/', $text, $match)

上面的表达式工作正常,但我试图一次性完成,而不是分开。我想这是我的OCD踢:/

php regex string preg-match
2个回答
0
投票

您可以使用捕获组:

$text = 'First string here(second here)';
if (preg_match('#^([^\(]+)\(([^\)]+)\)$#', $text, $match)) {
    print "$match[1]\n";
    print "$match[2]";
}

See demo on ideone


0
投票
$out= preg_split('/[\(\)]/',$text)[1];
© www.soinside.com 2019 - 2024. All rights reserved.