简单的正则表达式匹配php中格式变量= [[word]]中的单词

时间:2014-04-20 16:11:15

标签: php regex

我必须使用格式示例

搜索大量文本
traded_as = {{NASDAQ|GOOG}}<br>{{NASDAQ|GOOGL}}<br>[[Company name]]<br>.

文字的一般格式为variable = some text here [[ word ]] some text here。  有人可以帮助我使用一般的正则表达式,这种表达式只能让我只能在[[word]]中得到这个词,而不管它之前或之后的文本的性质。  我尝试在在线正则表达式测试人员的帮助下创建不同的Regx表达式,但是当它前面或之后的文本性质发生变化时,它会给我错误的匹配。

我试过的这个reqex表达式

$re1='.*?'; # Non-greedy match on filler
  $re2='((?:[a-z][a-z]+))'; # Word 1
  $re3='(\\s+)';    # White Space 1
  $re4='(=)';   # Any Single Character 1
  $re5='(\\s+)';    # White Space 2
  $re6='.*?';   # Non-greedy match on filler
  $re7='((?:[a-z][a-z]+))'; # Word 2

  if ($c=preg_match_all ("/".$re1.$re2.$re3.$re4.$re5.$re6.$re7."/is", $txt, $matches))
  {
      $word1=$matches[1][0];
      $ws1=$matches[2][0];
      $c1=$matches[3][0];
      $ws2=$matches[4][0];
      $word2=$matches[5][0];
      print "($word1) ($ws1) ($c1) ($ws2) ($word2) \n";
  }

2 个答案:

答案 0 :(得分:1)

尝试以下

preg_match('/\[\[([^]]*)\]]/', $txt, $match);
echo $match[1];

答案 1 :(得分:1)

<?php
    $string = "{{NASDAQ|GOOG}}<br>{{NASDAQ|GOOGL}}<br>[[Company name]]<br>";
    preg_match('/\[\[(.*?)\]\]/', $string, $regs);
        $result = $regs[1];
        echo $result;
        //Company name
?>

http://ideone.com/yH6eD9

Match the character “[” literally «\[»
Match the character “[” literally «\[»
Match the regular expression below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is not a line break character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “]” literally «\]»
Match the character “]” literally «\]»