Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP "str_replace" doesn't work properly in some case?

The below is the php code i am using

$file_handle = fopen("products.csv", "r");
$fname = "products.csv";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$server = "**\******,1433";
$connectionInfo = array( "Database"=>"******", "UID"=>"***", "PWD"=>"*******" );
$conn = sqlsrv_connect( $server, $connectionInfo ); 

if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

while (!feof($file_handle) ) {
    $line_of_text = fgetcsv($file_handle, 1024);
    $itemco = $line_of_text[0];
    $sql = "SELECT quantity FROM Item WHERE itemlookupcode = '$itemco' "; 
    $stmt = sqlsrv_query( $conn, $sql );

    if( $stmt === false) {
        die( print_r( sqlsrv_errors(), true) );
    }

    while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
        $icc = $row['quantity'];
        $content = str_replace("$line_of_text[1]", "$icc", "$content");
    }
}

$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);

str_replace isn't working in the following instance:

$content = str_replace("$line_of_text[1]", "$icc", "$content");
like image 880
Max Avatar asked Mar 28 '14 17:03

Max


5 Answers

First of all, you open the same file three times and only close it once. This is not a major problem but you really should make a habit of finishing/closing what you started. You can skip one of those fopen by using file_get_contents:

$content = file_get_contents("products.csv");

Now, str_replace will replace every occurrence of your string. If, for example, $line_of_text[1] is "11" and $icc is "9", other values in the file such as "110" will be affected, thus making the rest of future replacements less and less reliable each loop.

If I'm not mistaken and all you want to do is replace a single cell in each row, here's a suggestion: Create an empty variable, let's say $new_content

Now, change your loop:

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
    $line_of_text[1] = $row['quantity']; // change cell value
    $new_content .= implode(',', $line_of_text).','; // convert into string with extra
                                                     // ',' to avoid merging cells
}
$new_content = trim($new_content, ','); // remove extra ','
like image 60
Gil Avatar answered Oct 18 '22 01:10

Gil


Remove quotes around variables.

$content = str_replace("$line_of_text[1]", "$icc", "$content");

Should be

$content = str_replace($line_of_text[1], $icc, $content);

//str_replace ( search, replace, subject )   This is how it works.

Next,

Use this code corresponding to the while loop

$count=1;
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$icc = $row['quantity'];
$content = str_replace($line_of_text[$count++], $icc, $content);
}
like image 25
Sasanka Panguluri Avatar answered Oct 18 '22 02:10

Sasanka Panguluri


No debug output data.. I can only give some advice..

  • Does $line_of_text[1] and $icc output as expected values?
  • Does sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) returns a proper value? (If not it will won't do anything)
  • Hows your csv file structured?
like image 23
Sam Ye Avatar answered Oct 18 '22 03:10

Sam Ye


I'm not sure I understand, but there is no reason that str_replace does not work.
It may be just a matter of reasoning.
It does not work at all or only in some cases?
If it is in some cases, it may be because the replacement value no longer exists.

For example:

$content = "1234";
echo "$content\n"; // echo "1234"
$content = str_replace("1", "a", "$content");
echo "$content\n"; // echo "a1234"
$content = str_replace("2", "b", "$content");
echo "$content\n"; //  echo "ab34"
$content = str_replace("1", "c", "$content");
echo "$content\n";  // echo "ab34" => no change because '1' is not existe -> already replace

I do not know if this is your problem, but it could explain.

So may be you should do something like this:

$pos1 = stripos("$content", "$line_of_text[1]");
if ($pos1 !== false)
    $content = str_replace("$line_of_text[1]", "$icc", "$content");
else
    echo "$line_of_text[1] not found in $content \n";

Otherwise, I agree with the others, the double quotes are optional. :)

Good Luck.

like image 1
doydoy44 Avatar answered Oct 18 '22 01:10

doydoy44


$content = str_replace("$line_of_text[1]", "$icc", "$content");

this should be replaced with

$content = str_replace($line_of_text[1], $icc, $content);

since these are php variables and putting them in double or single quotes is incorrect, as they will be considered as normal text and str_replace will try to replace "$line_of_text[1]" with "$icc" in "$content".

like image 1
kkarayat Avatar answered Oct 18 '22 02:10

kkarayat