Reputation: 3692
I need remove all occurrences of text between brackets including themselves of lines.
I use a piece of code that was worth, until it appears more than one element
$array[] = '[2016-12-26 16:48:57 +0100] pkgacct working dir : /cprsync_back3/tamainut';
$array[] = '[2016-12-26 16:48:57 +0100] Copying SSL certificates, CSRs, and keys...[2016-12-26 16:48:57 +0100] Done'
foreach ($array as &$line) {
$line = preg_replace("/\[[^)]+\]/","",$line);
echo $line.PHP_EOL;
}
This works well with the first line, but not with the second line
pkgacct working dir : /cprsync_back3/tamainut
Done
What need for extract only [..] but conserving this [..] ?
Upvotes: 1
Views: 108
Reputation: 91373
Just replace the parenthesis by a bracket in the character class:
$line = preg_replace("/\[[^\]]+\]/","",$line);
// here __^
Upvotes: 1
Reputation: 48711
Regex:
\[[^][]*(?(?=\[)(?R))[^][]*\]
Explanation:
\[ # Match opening bracket
[^][]* # Match anything but `[` & `]` characters
(?(?=\[)(?R)) # If previous match ends before `[` repeat whole pattern
[^][]* # //
\] # Match closing bracket
This regex is supposed to work on nested brackets as well.
Code snippet:
preg_replace("@\[[^][]*(?(?=\[)(?R))[^][]*\]@", "", $line);
Upvotes: 1
Reputation: 1579
Take a look at the loop; also your regex needs a fix (note I've added ?
quantifier).
$array[
'[2016-12-26 16:48:57 +0100] pkgacct working dir : /cprsync_back3/tamainut',
'[2016-12-26 16:48:57 +0100] Copying SSL certificates, CSRs, and keys...[2016-12-26 16:48:57 +0100] Done'
];
foreach ($array as $key => $line) {
$array[$key] = preg_replace('/\[(.*?)\]/', "", $line);
}
echo '<pre>';
print_r($array);
Upvotes: 1