简体   繁体   中英

Extracting two strings from a string using preg_match

I'm trying to extract two string from a string. The format of the string is as follows:

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

The seconds string will always be at the end within quotes. I'm trying to extract them efficiently. I've tried using this: preg_match('#\\((.*?)\\)#', $text, $match) and preg_match('/\\(([^\\)]+)\\)/', $text, $match)

The above expressions work fine, but I'm trying to do it in one go, not separately. I guess it's my OCD kicking in :/

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

You can use capture groups:

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

See demo on ideone .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM