如何从PHP中的括号之间获取所有内容?

时间:2010-09-08 12:42:31

标签: php regex arrays string preg-match

Array(
[1] => put returns (between) paragraphs
[2] => (for) linebreak (add) 2 spaces at end
[3] => indent code by 4 (spaces!)
[4] => to make links
)

想要在括号内获取文字(对于每个值):

  1. 仅参加第一场比赛
  2. 从值
  3. 中删除此匹配项
  4. 将所有匹配项写入新数组
  5. 函数数组后应如下所示:

    Array(
    [1] => put returns paragraphs
    [2] => linebreak (add) 2 spaces at end
    [3] => indent code by 4
    [4] => to make links
    )
    Array(
    [1] => between
    [2] => for
    [3] => spaces!
    [4] => 
    )
    

    解决方案是什么?

2 个答案:

答案 0 :(得分:2)

假设您的意思是(between)而不是((between))

$arr = array(
                0 => 'put returns (between) paragraphs',
                1 => '(for) linebreak (add) 2 spaces at end',
                2 => 'indent code by 4 (spaces!)',
                3 => 'to make links');
var_dump($arr);

$new_arr = array();
foreach($arr as $key => &$str) {
        if(preg_match('/(\(.*?\))/',$str,$m)) {
                $new_arr[] = $m[1]; 
                $str = preg_replace('/\(.*?\)/','',$str,1);
        }   
        else {
                $new_arr[] = ''; 
        }   
}
var_dump($arr);
var_dump($new_arr);

Working link

答案 1 :(得分:2)

我会使用正则表达式/\((\([^()]*\)|[^()]*)\)/(这将匹配一对或两对括号)和preg_split

$matches = array();
foreach ($arr as &$value) {
    $parts = preg_split('/\((\([^()]*\)|[^()]*)\)/', $value, 2, PREG_SPLIT_DELIM_CAPTURE);
    if (count($parts) > 1) {
        $matches[] = current(array_splice($parts, 1, 1));
        $value = implode('', $parts);
    }
}

preg_split PREG_SPLIT_DELIM_CAPTURE 标志设置一起使用将包含结果数组中匹配的分隔符。所以找到了匹配,至少有三个部分。在这种情况下,第二个成员是我们正在寻找的成员。该成员将被array_splice删除,该成员也会返回已删除成员的数组。要获取已删除的成员,array_splice的返回值将使用current。然后将其余成员放回原处。