检测字符串中的括号模式

时间:2011-11-28 22:02:08

标签: php regex preg-match

检测字符串中的括号模式

  

这是一条线(括号之间的一个例子)。

  

这是一条线(括号之间的一个例子)。

我需要将两个字符串分开:

  

$ text ='这是一行。';

     

$ eg ='括号之间的一个例子';

到目前为止我有这个代码:

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

但它只会将文本带入括号内。我还需要括号外的文字。

4 个答案:

答案 0 :(得分:3)

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

更新 ..现在有许多括号:

$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 . "\n";
echo "parenthesis content: " . print_r($parenthesis,1) . "\n";

结果:

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

答案 1 :(得分:1)

您可以将preg_split用于此特定任务。如果在关闭括号后没有文本,则忽略最后一个数组值。

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

答案 2 :(得分:0)

所有文字都应在$match[0]中。如果你想获得之前的文本和之后的文本,只需像这样重写你的正则表达式:

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

然后。之前的文字将在$match[1]$match[3]

答案 3 :(得分:0)

我认为您可以尝试使用此正则表达式([^\(].[^\(]*)(\(\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