Hello,
I am trying to find / replace a line in a text file where the frist value must be replaced based on the second value and the second value must be replaced always with "1".
<CUSTOMER cust_sid="ABCDEFGH123" sbs_no="100" cust_id="123455678" store_no="2" status="0">
I need to replace sbs_no="100" with sbs_no="102" which is the value of sbs_no="100" plus store_no="2"
and the old value of store_no="2" must be allways store_no="1".
So, the new line should be:
<CUSTOMER cust_sid="ABCDEFGH123" sbs_no="102" cust_id="123455678" store_no="1" status="0">
I really appreciate any help. Thanks in advance.
Marcelo.
Find / replace value based on second value same line
Moderator: General Moderators
- andyhoneycutt
- Forum Contributor
- Posts: 468
- Joined: Wed Aug 27, 2008 10:02 am
- Location: Idaho Falls
Re: Find / replace value based on second value same line
Not sure if you're trying to do this with one line of regex, but here's a solution that seems to work...may need to tweak it a bit for your file format:
-Andy
Code: Select all
<?php
$file = file("myfile.txt");
$new_file = fopen("newfile.txt","w");
$pattern = "/([a-zA-Z\_]+)=\"([A-Z0-9]+|[0-9]+)\"/";
foreach($file as $subject)
{
$output = $subject;
$matches = array();
preg_match_all($pattern,$subject,$matches);
if( count($matches) == 3 )
{
$keys = $matches[1];
$values = $matches[2];
$data = array_combine($keys,$values);
$new_sbs_no = $data['sbs_no'] + $data['store_no'];
$output = "<CUSTOMER cust_sid=\"{$data['cust_sid']}\" " .
"sbs_no=\"$new_sbs_no\" " .
"cust_id=\"{$data['cust_id']}\" " .
"store_no=\"1\" status=\"{$data['status']}\">\n";
}
fputs($new_file,$output);
}
fclose($new_file);