preg_match一行中的所有事件

时间:2015-02-04 09:09:30

标签: php regex preg-match

示例(file = xref.tex)

This is a example string and first line with <xref>id1</xref>then,<xref>id2</xref>and with no line breaks<xref>id3</xref>.
This is a second line which has <xref>id4</xref>

示例(file = id)

id1 eqvalue1
id2 eqvalue2
id3 eqvalue3
id4 eqvalue4

要求:每个唯一ID都具有等效值。我需要在“xref.tex”文件中每次出现时替换id中的等效值。

到目前为止已经尝试过:

    $xref=file("xref.tex");
    $idfile=file("id");
    for($y=0;$y<count($xref);$y++){
      for($z=0;$z<count($idfile);$z++){
        $idvalue=explode(" ",$idfile[$z])//exploding based on space charac
        $id1=$idvalue[0]; //this is equivalent value of unique id
        $id2=$idvalue[1];  // this is unique id
        preg_match( '/<xref>(.*?)<\/xref/', $xref[$y], $match );
        //getting the content between "<xref>"and "</xref>"
        if($match[1]===$id2{
          $xref[$y]=str_replace($match[1],$id1,$xref[$y]);}
          //here first occurrence of id is replaced. how to replace  
          //second occurrence of id in a line as  
          //preg_match( '/<xref>(.*?)<\/xref/', $xref[$y], $match )
          //this regex focusing on first occurrence only every time.
          //???? prob here is how can i do this logic in all the occurrences 
          //in each line 
        }
     }
   }

预期输出:

This is a example string and first line with <xref>eqvalue1</xref>then,<xref>eqvalue2</xref>and with no line breaks<xref>eqvalue3</xref>.
This is a second line which has <xref>eqvalue4</xref>

3 个答案:

答案 0 :(得分:0)

阅读文件&#34; id&#34;将csv空间分隔为数组,然后使用file_get_contents将该数组与另一个文件中的preg_replace一起用作字符串。

答案 1 :(得分:0)

试试这个:

$re = "/(<xref>[^\\d]+)(\\d)(<\\/xref)/m";
$str = "This is a example string and first line with <xref>id1</xref>then,<xref>id2</xref>and with no line breaks<xref>id3</xref>. This is a second line which has <xref>id4</xref>";
$subst = "$1eqvalue$2$3";

$result = preg_replace($re, $subst, $str);

Live demo

答案 2 :(得分:0)

这是我的理解。文件 xref.tex 的内容如下

<xref>id1</xref><xref>id2</xref><xref>id3</xref><xref>id4</xref> //line 1
<xref>id2</xref><xref>id3</xref> //line 2
<xref>id4</xref> //line 3
... and so on

首先,你必须修复正则表达式。您在结尾处遗漏了>。它应该是

/<xref>(.*?)<\/xref>/

然后您需要按照建议使用preg_match_all而不是preg_match

我已经修改了一点代码。如果您在一行中重复相同的ID,这也应该有用。

$xref=file("xref.tex");
$idfile=file("id");
for($y=0;$y<count($xref);$y++)
{
    preg_match_all( '/<xref>(.*?)<\/xref/', $xref[$y], $match ); //get all matches and store them in *match*
    for($z=0;$z<count($idfile);$z++)
    {
        $idvalue=explode(" ",$idfile[$z]);
        $id1=$idvalue[0]; 
        $id2=$idvalue[1];  
        //Below, we're replacing all the matches in line with corresponding value. Edit: Maybe not the best way, but it will give you an idea.
        foreach($match[0] as $matchItem)
            $xref[$y]=str_replace($matchItem,$id1,$xref[$y]);
    }    
}

修改

您可能需要查看preg_replace。我认为这将是一个更好的解决方案。