检测字符串中的括号模式

Detecting a parenthesis pattern in a string

This is a line (an example between parenthesis).

or

This is a line(an example between parenthesis).

I need to separate both strings in:

$text = 'This is a line.';

$eg = 'an example between parenthesis';

I have this code so far:

$text = 'This is a line (an example between parenthesis)';
preg_match('/\((.*?)\)/', $text, $match);
print $match[1];

But it only brings the text inside the parenthesis. I also need the text outside the parenthesis.

$text = 'This is a line (an example between parenthesis)';
preg_match('/(.*)\((.*?)\)(.*)/', $text, $match);
echo "in parenthesis: " . $match[2] . "
";
echo "before and after: " . $match[1] . $match[3] . "
";

UPDATE after clarification of question .. now with many parenthesis:

$text = "This is a text (is it?) that contains multiple (example) stuff or (pointless) comments in parenthesis.";
$remainder = preg_replace_callback(
        '/ {0,1}\((.*)\)/U',
        create_function(
            '$match',
            'global $parenthesis; $parenthesis[] = $match[1];'
        ), $text);
echo "remainder text: " . $remainder . "
";
echo "parenthesis content: " . print_r($parenthesis,1) . "
";

results in:

remainder text: This is a text that contains multiple stuff or comments in parenthesis.
parenthesis content: Array
(
    [0] => is it?
    [1] => example
    [2] => pointless
)

All the text should be in $match[0]. If you want to get the text before and the text after, simply rewrite your regex like so:

/(.*?)\((.*)\)(.*?)/

Then. the text before will be in $match[1] and $match[3].

I think you can try with this regex ([^\(].[^\(]*)(\(\b[^\)]*(.*?)\)):

<?php
$text = 'This is a line (an example between parenthesis)';

preg_match_all('/([^\(].[^\(]*)(\(\b[^\)]*(.*?)\))/', $text, $match);

echo '<pre>';
print_r($match);
echo '<pre>';

$text = 'This is a line(an example between parenthesis)
This is a line (an example between parenthesis)
This is a line (an example between parenthesis)
This is a line (an example between parenthesis) This is a line (an example between parenthesis) This is a line (an example between parenthesis)';

preg_match_all('/([^\(].[^\(]*)(\(\b[^\)]*(.*?)\))/', $text, $match);

echo '<pre>';
print_r($match);
echo '<pre>';
?>

http://codepad.viper-7.com/hSCf2P

You could use preg_split for this specific task. Ignore last array value if ther is no text after closing parenthesis.

$text = 'This is a line (an example between parenthesis)';
$match = preg_split('/\s*[()]/', $text);