在字符串内搜索
问题描述:
$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
- 删除[...]自变量(擦除)的所有比赛
- 仅删除第一场比赛
- 只删除最后一场比赛
尝试不同的正则表达式这一点,像/[\(.*?\)]/
,但结果不是人们所预料的。
答
这应做到:
$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函数来代替标签,标签的所有类似OCCURENCES将如果这样的存在,而不只是第取出。
试试这个'/ \\ [([^ \\] *)\\] /' – jcubic 2010-09-17 10:37:37
@jcubic,有什么区别? – James 2010-09-17 10:51:42
括号是特殊的正则表达式字符,如果你想匹配括号,你必须转义它。 – jcubic 2010-09-17 11:19:32