$variable = 'of course it is unnecessary [http://google.com],
but it is simple["very simple"], and this simple question clearly
needs a simple, understandable answer [(where is it?)] in plain English'
每次更改时此变量的值。
我要做的是从[...]
获取文字。因此,如果有[(google)]
,则匹配应为(google)
。
我正在寻找一种解决方案,可以执行以下每项操作:
$all
$first
$last
为此尝试了不同的正则表达式,例如/[\(.*?\)]/
,但结果并非人们所期望的结果。
答案 0 :(得分:2)
这应该这样做:
$variable = 'of course it is unnecessary [http://google.com],
but it is simple["very simple"], and this simple question clearly
needs a simple, understandable answer [(where is it?)] in plain English';
preg_match_all("/(\[(.*?)\])/", $variable, $matches);
$first = reset($matches[2]);
$last = end($matches[2]);
$all = $matches[2];
# To remove all matches
foreach($matches[1] as $key => $value) {
$variable = str_replace($value, '', $variable);
}
# To remove first match
$variable = str_replace($first, '', $variable);
# To remove last match
$variable = str_replace($last, '', $variable);
请注意,如果您使用str_replace替换标记,那么标记的所有相似出现都将被删除(如果存在),而不仅仅是第一个。