views:

60

answers:

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

Want to get text inside brackets (for each value):

  1. take only first match
  2. remove this match from the value
  3. write all matches to new array

After function arrays should look like:

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] => 
)

What is the solution?

+1  A: 

Assuming you meant (between) and not ((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

codaddict
+1  A: 

I would use the regular expression /\((\([^()]*\)|[^()]*)\)/ (this will match one or two pairs of parentheses) together with 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);
    }
}

Using preg_split with PREG_SPLIT_DELIM_CAPTURE flag set will contain the matched separators in the result array. So a match was found, there are at least three parts. In that case the second member is the one we are looking for. That member is removed with array_splice that does also return the array of removed members. To get the removed member, current is used on the return value of array_splice. The remaining members are then put back together.

Gumbo