2010-09-17 145 views
1
$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)

我在寻找一个解决方案,它可以做这些动作:

  1. 获得的所有比赛[...],写入$all
  2. 只得到第一比赛,写入$first
  3. 只得到最后比赛,写入$last
  4. 删除[...]自变量(擦除)的所有比赛
  5. 仅删除第一场比赛
  6. 只删除最后一场比赛

尝试不同的正则表达式这一点,像/[\(.*?\)]/,但结果不是人们所预料的。

+0

试试这个'/ \\ [([^ \\] *)\\] /' – jcubic 2010-09-17 10:37:37

+0

@jcubic,有什么区别? – James 2010-09-17 10:51:42

+0

括号是特殊的正则表达式字符,如果你想匹配括号,你必须转义它。 – jcubic 2010-09-17 11:19:32

回答

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函数来代替标签,标签的所有类似OCCURENCES将如果这样的存在,而不只是第取出。

+0

应该有一种方法来删除所有,第一次或只有最后一次匹配 – James 2010-09-17 10:38:08

+0

** $ first **是** [(它在哪里?)] **它应该是**(它在哪里?)** (删除[和]) – James 2010-09-17 10:40:58

+0

@快乐,这是固定的,有错误的关键。 – 2010-09-17 10:44:29