Angelin Calu
Angelin Calu

Reputation: 1915

PHP Preg_replace doesn't seem to work for me

I have a number of files that has parts that need to be replaced. An example of such a file is:


    u101p-fr-2_2
    PAN,  'U101P-FR-2_2', P, BLO='U101P', DT=101, X=FR-2, AS4='M';
    CUR,  'CB1', COL=MAGENTA, LTY=SOLID, YZ, 6390.45,5985.01/
          0, 7341.23,6752.51/
          0, 7341.22,6752.5/
          R400.01, 7489.98,7063.74/
          0, 7489.98,8863.99;
    BOU,  'U101P-Y7800', SID=SB/ 'U101P-Z8800', SID=BOT/ 'CB1'/ Z=7063.74;
    PLA,  MAT=20, MSI=FOR, QUA=A, POS=179, NO=1, AS4='P';
    FLA,  PRO=10,200,20, CUR, LIM=3, QUA=A, POS=734, NO=1, COL=YELLOW, 
          CON=15, CUT=1100, EXC=30/ CON=45, CUT=1402,30;
    EXC,  TYP=TIP1, LIM=4, M1=30;
    NOT,  R50, COR=2;

For this particular example I have to replace POS=179 to POS=115 and POS=734 to POS=762.

I can do it with Notepad++ using something like: \bPOS\=179\b Also, it seems to work on different websites like http://regexr.com?33hti

However, in PHP, using preg_replace it does NOT WORK. Any help would be greatly appreciated!

Upvotes: 1

Views: 214

Answers (2)

mario
mario

Reputation: 145512

So, you finally decided to divulge your code:

foreach (glob($path_SCH_ModelBun.$unitatea."/*.sch") as $filename){ 
  $file = file_get_contents($filename);
  echo "<pre>".$file."</pre><br /><br />";
  $search_for = "/\bPOS".preg_quote("=".$search_for)."\b/g";
  $replace_with= "POS=".$replace_with;
  echo $res = preg_replace($search_for, $replace_with ,$file);
  echo " <pre>".$file."</pre> ";
}

You are incorrectly using the /g flag. Enable error_reporting to learn why your regex fails. PHPs PCRE does not support that.

Also you are using $res = for assigning the modified file contents back. But then you are writing out the unmodified original $file out again.

Upvotes: 2

nice ass
nice ass

Reputation: 16729

I believe that if I have POS=2 and POS=21, per example it will alter the results

You can use strtr to avoid that:

Example:

$string = 'POS 2 POS 21 POS 27 POS 2 POS 21';

print strtr($string, array(
  'POS 27' => 'POS 420',          // find => replace
  'POS 2'  => 'POS 5',
  'POS 21' => 'POS 7',
));

The longest matches will be replaced first, so you won't run into any problems.

Upvotes: 0

Related Questions