`preg_match_all()`产生错误/ null结果

时间:2011-12-30 09:17:34

标签: php regex serialization preg-match-all recursive-regex

问题

为什么我得到错误的结果?我怎样才能得到理想的结果?

输入文件

vulture (wing)
tabulations: one leg; two legs; flying
father; master; patriarch
mat (box)
pedistal; blockade; pilar
animal belly (oval)
old style: naval
jackal's belly; jester    slope of hill (arch)
key; visible; enlightened

代码的两个版本,有问题

版本1:

<?php
$filename = "fakexample.txt";
$file = fopen($filename, "rb");
$myFile = fread($file, filesize($filename));
//PLEASE NOTE THAT $STARTSAFE IS IN PLACE IN THIS VERSION AND NOT IN THE NEXT
function get_between($startString, $endString, $myFile, $startSafe, $endSafe){
  //CHANGES WILL START HERE
  if($startSafe = 0){
    $startStringSafe = $startString;
  }
  elseif($startSafe = 1){
    $startStringSafe = preg_quote($startString, '/');
  }
  //AND END HERE
  if($endSafe = 0){
    $endStringSafe = $endString;
  }
  elseif($endSafe = 1){
    $endStringSafe = preg_quote($endString, '/');
  }
  //non-greedy match any character between start and end strings. 
  //s modifier should make it also match newlines.
  preg_match_all("/$startStringSafe(.*?)$endStringSafe/m", $myFile, $matches);
  return $matches;
}
$list = get_between("^", ")", $myFile, 0, 1);
foreach($list[1] as $list){
  echo $list."\n";
}
?>

此代码不返回任何内容。

第2版:

<?php
$filename = "fakexample.txt";
$file = fopen($filename, "rb");
$myFile = fread($file, filesize($filename));
//PLEASE NOTE THAT $STARTSAFE IS NOT IN PLACE IN THIS VERSION
function get_between($startString, $endString, $myFile, $startSafe, $endSafe){
  //CHANGES START HERE

    $startStringSafe = $startString;



  //AND END HERE
  if($endSafe = 0){
    $endStringSafe = $endString;
  }
  elseif($endSafe = 1){
    $endStringSafe = preg_quote($endString, '/');
  }
  //non-greedy match any character between start and end strings. 
  //s modifier should make it also match newlines.
  preg_match_all("/$startStringSafe(.*?)$endStringSafe/m", $myFile, $matches);
  return $matches;
}
$list = get_between("^", ")", $myFile, 0, 1);
foreach($list[1] as $list){
  echo $list."\n";
}
?>

返回vulture (wing mat (box animal belly (oval jackal's belly; jester slope of hill (arch

所需的输出

vulture mat animal belly jackal's belly; jester slope of hill

标记差异

vulture **(wing** mat **(box** animal belly **(oval** jackal's belly; jester slope of hill **(arch**

1 个答案:

答案 0 :(得分:3)

^表示默认情况下开始主题。如果您希望它表示行首,那么您必须在正则表达式包装中使用/m modifier