Search code examples
phpregexpreg-match

preg_match all the occurrences in a line


Example (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>

Example (file=id):

id1 eqvalue1
id2 eqvalue2
id3 eqvalue3
id4 eqvalue4

Requirement: Every unique id has a equivalent value. I need to replace that equivalent value in the place of id in each occurrences in "xref.tex" file.

Tried so far:

    $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 
        }
     }
   }

Expected output:

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>

Solution

  • Here is what I understand. The contents of the file xref.tex is as follows

    <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
    

    First of all, you have to fix the regex. You're missing > at the end of it. It should be

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

    Then you need to use preg_match_all instead of preg_match as suggested.

    I've modified the code a little bit. This should also work if you have same id repeating in a single line.

    $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]);
        }    
    }
    

    EDIT

    You might want to check preg_replace. I think that would be a better solution.