在字符串中搜索

时间:2010-09-17 10:27:25

标签: php string search

$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 匹配,并写入$last
  4. 从变量(擦除)中删除[...]的所有匹配项
  5. 仅删除第一场比赛
  6. 仅删除最后一场比赛
  7. 为此尝试了不同的正则表达式,例如/[\(.*?\)]/,但结果并非人们所期望的结果。

1 个答案:

答案 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替换标记,那么标记的所有相似出现都将被删除(如果存在),而不仅仅是第一个。