检测字符串中的括号模式


Detecting a parenthesis pattern in a string

检测字符串中的括号模式

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

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

我需要分隔两个字符串:

$text = 'This is a line.'

$eg = 'an example between parenthesis';

到目前为止,我有以下代码:

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

但是它只把文本放在括号内。我还需要括号外的文本

$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";

UPDATE澄清问题后…现在有很多括号:

$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
)

你可以使用preg_split这个特定的任务。如果右括号后没有文本,则忽略最后一个数组值。

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

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

/(.*?)'((.*)')(.*?)/

。之前的文本将在$match[1]$match[3]

我想你可以试试这个正则表达式([^'(].[^'(]*)('('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