簡體   English   中英

使用preg_match從字符串中提取兩個字符串

[英]Extracting two strings from a string using preg_match

我試圖從一個字符串中提取兩個字符串。 字符串的格式如下:

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

秒字符串將始終在引號內的末尾。 我正在嘗試有效地提取它們。 我試過使用此: preg_match('#\\((.*?)\\)#', $text, $match)preg_match('/\\(([^\\)]+)\\)/', $text, $match)

上面的表達式工作正常,但我想一次性完成,而不是單獨進行。 我猜是我的強迫症發作了:/

$out= preg_split('/[\(\)]/',$text)[1];

您可以使用捕獲組:

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

參見有關ideone的演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM