PHP, problem with str_replace when reading from an array

I am new to php and I am trying to make a script that reads a CSV file (file1.csv) and compares the words in the file with the words in the html file (file2.html) if the word in file2.html matches the key part in file1. csv, it should change the contents of file2.html with the value of the matching key.

what i have done so far:

$glossArray = array();
$file_handle = fopen("file1.csv", "r");
while (!feof($file_handle) ) {

    $line_of_text = fgetcsv($file_handle, 10000,';');
    $glossArray[$line_of_text[0]] =  $line_of_text[1];
    $counter++;
}
fclose($file_handle);

$file = file_get_contents("file2.html");

foreach($glossArray as $key => $value){
    $results = str_replace($key," means ".$value ,$file);
}

echo $results;

I think my problem occurs when I try to iterate and change the values ​​.. because I only see the contents of file2.html without changes

any help would be appreciated

early

Nader

Ps I edited the old code with the new one after your valuable advice .. now it is like this .. but still does not work.

Update: changing foreach with:

$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);

.. : , , "" .

+3
5

$glossArray str_replace . , str_replace, . , - :

$results = $file;
foreach($glossArray as $index=>$value)
{
    $results = str_replace($index,$value ,$results);

}

str_replace ( ), - :

$results = str_replace(array_keys($glossArray), array_values($glossArray), $file);
+4

, foreach. :

foreach($glossArray as $key => $value){
    $results = str_replace($key,$value ,$file);
}

, $glossArray $. !

+4

file2.html , ?

(BTW - )

foreach($glossArray as $value)
{
  $results = str_replace($glossArray,$value ,$file);

,

foreach($glossArray as $old=>$new)
{
   $results = str_replace($old, $new, $file);

2 , str_replace .

+3

str_replace $glossArray , , .

, CSV - "SEARCH; REPLACE"? foreach : foreach ($glossArray as $searchString => $value).

$file = str_replace($searchString, $value ,$file);

$results = str_replace($searchString, $value ,$file);

$results str_replace... echo $file, .

BTW: $counter?

+1

The solution to your new problem (in fact, it should be your own question, not editing the existing one) is that array_values ​​returns an array, and when you combine an array with a string, php inserts 'Array' instead of a value.

$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);

wrong. You should do this instead:

$vals = array_values($glossArray);
foreach($vals as $k=>$v)$vals[$k] = 'means '.$v;
$results = str_replace(array_keys($glossArray), $vals, $file);

Note that glossArray values ​​are retrieved, and each value is concatenated with your string - if you just try to combine the string with an array, you will get a string, not aray.

0
source

Source: https://habr.com/ru/post/1773244/


All Articles