支架之间的php preg_match

时间:2011-10-11 17:12:49

标签: php string preg-match

我想使用preg_match在括号之间查找文本,例如:$varx = "(xx)";

最终输出为$match = 'xx';

另一个例子$varx = "bla bla (yy) bla bla";

最终输出将类似于此$match = 'yy';

换句话说,它剥去了支架。我仍然对正则表达式感到困惑,但发现有时preg match是更简单的解决方案。寻找其他例子但不符合我的需要。

6 个答案:

答案 0 :(得分:8)

尝试这样的事情:

preg_match('/(?<=\()(.+)(?=\))/is', $subject, $match);

现在它将捕获换行符。

答案 1 :(得分:7)

请记住,括号是RegExps中的特殊字符,因此您需要使用反斜杠转义它们 - 您还没有明确说明( ... )之间可能出现的字符范围或是否( ... )可以有多个实例。

因此,您最好的选择可能是RegExp,例如:/\(([^\)]*)\)/,它会匹配括号中包含任何(或没有)字符的( ... )的多次出现。

尝试preg_match('/\(([^\)]*)\)/', $sString, $aMatches)

编辑:(示例)

<?php
$sString = "This (and) that";
preg_match_all('/\(([^\)]*)\)/', $sString, $aMatches);
echo $aMatches[1][0];
echo "\n\n\n";
print_r($aMatches);
?>

结果是:

and


Array
(
    [0] => Array
        (
            [0] => (and)
        )

    [1] => Array
        (
            [0] => and
        )

)

所以字符串“和”存储在$ aMatches [1] [0]:)

答案 2 :(得分:3)

preg_match('/\((.*?)\)/i', $varx, $match);

添加s修饰符允许括号之间的换行符。例如:

bla bla (y
y) bla bla

preg_match('/\((.*?)\)/si', $varx, $match);

如果paraentheses之间的内容具有规则模式,则可以构建更好的表达。例如,如果它总是像xx或yy这样的双字母,则以下表达式将是更好的匹配。

/\(([a-zA-Z]{2})\)/i

此外,如果您要在$varx中捕获所有匹配,请使用preg_match_all()。例如:

this (and) that (or) the other

preg_match_all()将捕获andor

要测试它,请使用以下内容:

<?php
$varx = "this (and) that (or) the other";
preg_match_all('/\((.*?)\)/si', $varx, $matches);
print_r($matches);
?>

这将显示匹配在$matches数组中的位置。

答案 3 :(得分:2)

我希望这有效

preg_match_all('#\(((?>[^()]+)|(?R))*\)#x');

对不起答案我很抱歉..

$preg_match = '#\(((?>[^()]+)|(?R))*\)#x';

$data = 'bla bla (yy) bla bla';

if(preg_match_all($preg_match, $data, $match)) {
    $match = $match[0];
} else {
    $match = array();
}

希望现在有意义

答案 4 :(得分:2)

这看起来更清晰。

$pattern = '/\((.+?)\)/is';

答案 5 :(得分:1)

请勿使用正则表达式,请使用str_replace()

$string = str_replace(array('(', ')'), '', $your_string);