Array(
[1] => put returns (between) paragraphs
[2] => (for) linebreak (add) 2 spaces at end
[3] => indent code by 4 (spaces!)
[4] => to make links
)
想要在括号内获取文字(对于每个值):
函数数组后应如下所示:
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] =>
)
解决方案是什么?
答案 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);
答案 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
。然后将其余成员放回原处。