PHP:如何只获取括号()之间的单词并清除其他所有单词

时间:2009-04-09 19:46:44

标签: php

我有一个包含一些信息的数组。例如:

  

(作家)&

  

(附加对话)

我想清理这个,所以我只得到括号()之间的文本并清除其他所有内容

结果:

  

作家

  

额外对话

5 个答案:

答案 0 :(得分:12)

最简单的方法是使用正则表达式:

preg_match_all('/\((.*?)\)/', $input, $matches);

$matches[1]$matches[2]等将包含$ input中括号之间的所有内容。也就是说,$matches[1]将具有第一组括号之间的任何内容,依此类推(以处理具有多个集合的案例)。

答案 1 :(得分:8)

$string = "this (is (a) test) with (two parenthesis) duh";

对于这样的字符串,您可以使用preg_match_all并使用implode。

$string = "this (is (a) test) with (two parenthesis) duh";
$regex = '#\((([^()]+|(?R))*)\)#';
if (preg_match_all($regex, $string ,$matches)) {
    echo implode(' ', $matches[1]);
} else {
    //no parenthesis
    echo $string;
}

或者您可以使用preg_replace,但是如果使用多个括号,则会丢失它们之间的空格。

$regex = '#[^()]*\((([^()]+|(?R))*)\)[^()]*#';
$replacement = '\1';
echo preg_replace($regex, $replacement, $string);

我从这个页面Finer points of PHP regular expressions获得了很多帮助。

答案 2 :(得分:1)

$matches = array();
$num_matched = preg_match_all('/\((.*)\)/U', $input, $matches);

答案 3 :(得分:1)

function getInbetweenStrings($start, $end, $str){
    $matches = array();
    $regex = "/$start([a-zA-Z0-9_]*)$end/";
    preg_match_all($regex, $str, $matches);
    return $matches[1];
}

例如,您希望在以下示例中{}之间的字符串(键)数组,其中'/'不介于其中

$str = "C://{ad_custom_attr1}/{upn}/{samaccountname}";
$str_arr = getInbetweenStrings('{', '}', $str);

print_r($str_arr);

答案 4 :(得分:0)

在替换中使用上面

echo preg_replace('/\(([\w]{1,2})\)/',"(s\\1)",'(Gs) Main Hall');

结果

(sGs) Main Hall