user1989
user1989

Reputation: 163

Replace value in php not works as expected

I am having a file like this and I am trying to replace the file:

abc.txt

# Define the right-hand side of the equation:
#{xvalue1#}xval1= ;#xvalue1
#{xvalue2#}xval2= ;#xvalue2

What I did is as follows:

$myfile = fopen("abc.txt", "r") or die("Unable to open file!");
$data = fread($myfile,filesize($pgm_file));

function get_string_between($string, $start, $end){
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}

$parsed0 = get_string_between($data, "#{xvalue1#}xval1=", ";#xvalue1");
$parsed1 = get_string_between($data, "#{xvalue2#}xval2=",";#xvalue2");

I am trying to replace the values as follows:

$datanew0 = str_replace($parsed0,"5", $data);
$datanew1 = str_replace($parsed1,"10", $datanew0);

When I echoed echo $datanew1; I am getting output as :

# Define the right-hand side of the equation:
    #{xvalue1#}xval1= 5;#xvalue1
    #{xvalue2#}xval2= 5;#xvalue2

My expected result is:

# Define the right-hand side of the equation:
    #{xvalue1#}xval1= 5;#xvalue1
    #{xvalue2#}xval2= 10;#xvalue2

Upvotes: 2

Views: 46

Answers (2)

Halayem Anis
Halayem Anis

Reputation: 7785

Why not using RegEx ? it is more appropriate, efficient and maintainable implementation :

<?php
    $subject = "#{xvalue1#}xval1= 19;#xvalue1";
    $pattern = "/#\{xvalue[0-9]+#\}xval[0-9]+= ([0-9]+);#xvalue[0-9]+/";
    preg_match_all($pattern, $subject, $matchs);
    var_dump($matchs);

EDIT: I suggest you to change your pattern like this :

#{xvalue#}xval1= ;#xvalue

And the RegEx pattern will be :

$pattern = "/#\{xvalue#\}xval([0-9]+)= ([0-9]+);#xvalue/";

Note that i have also captured the key associated to your value

Upvotes: 0

m02ph3u5
m02ph3u5

Reputation: 3161

I'd recommend to rather work with the positions within the string than extracting and replacing stuff.

Take a look at this example

function injectBetween($what, $start, $end, $src){
    $lpos = strpos($src, $start);
    $rpos = strrpos($src, $end);
    return substr($src, 0, $lpos + strlen($start)) . $what . substr($src, $rpos);
}

var_dump(injectBetween('test', 'start', 'end', 'startend'));

Will give you string 'starttestend' (length=12)

Or to match your example:

var_dump(injectBetween('5', '#{xvalue1#}xval1= ', ';#xvalue1', '#{xvalue1#}xval1= ;#xvalue1'));

I don't know how your full input looks like. If you have multiple lines that have the same pattern this will most probably fail. Better use regular expressions in that case or parse your input line by line (using explode()).

Upvotes: 1

Related Questions