PHP, problem with str_replace while reading from array - php

i am new to php, and i am trying to do a script that reads an CSV file(file1.csv) and compare the words in the file with words in a html file (file2.html), if word in file2.html match with the key part in file1.csv it should change the file2.html contents with the value of the key matched ..
what i have done so far is this :
$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 that my problem occurs when i try to iterate and change values .. because what i see is only the contents of file2.html unchanged
any help would be appreciated
thank you in advance
Nader
P.s. i edited the old code with the new one after your valuable advise .. now it's like this .. but still doesnt work.
Update: changing the foreach with :
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
solved the problem .. but another one comes up: now every time it replaces a string it adds the word 'Array' ahead of it.

You're passing the entire $glossArray in to str_replace each time. You're also passing the initial file contents in each time you do str_replace, so at most you'd see one replacement. I think you want to change to something like this:
$results = $file;
foreach($glossArray as $index=>$value)
{
$results = str_replace($index,$value ,$results);
}
Since str_replace allows arrays for the first two parameters (as another user mentions) you could also do something like this instead of a loop:
$results = str_replace(array_keys($glossArray), array_values($glossArray), $file);

Yes, the problem is in your second foreach. It should read like this:
foreach($glossArray as $key => $value){
$results = str_replace($key,$value ,$file);
}
You forgot the key, so it's replacing every instance of every value in $glossArray with the $value. Good luck with that!

Why are you opening file2.html for reading and writing, then grabbing the contents of it?
(BTW - this is going to go horribly wrong on a system with strict locking)
foreach($glossArray as $value)
{
$results = str_replace($glossArray,$value ,$file);
I think this should be
foreach($glossArray as $old=>$new)
{
$results = str_replace($old, $new, $file);
Although it would be a lot more efficient to load the pairs from the glossary into 2 seperate numbered arrays, then just call str_replace once.

Your first parameter for str_replace should not be $glossArray as that's an array and not the string to replace.
I assume that your CSV-file contains something like "SEARCH;REPLACE"? In that case, your foreach should look like this: foreach ($glossArray as $searchString => $value).
Then try
$file = str_replace($searchString, $value ,$file);
instead of
$results = str_replace($searchString, $value ,$file);
because right now you're overwriting $results again and again with every str_replace ... echo $file when you're done.
BTW: What's $counter doing?

The solution to your new problem (which should really be it's own question, not an edit of the existing one) is that array_values returns an array, and when you concatenate an array with a string, php inserts 'Array' instead of the value.
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
is incorrect. 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);
Notice that the values of glossArray are extracted, and each value concatenated with your string - if you just try and concatenate the string with the array, you'll get a string, not an aray.

Related

PHP cURL string get everything before and after certain part of string

Im usin cURL to crabb some data from webpage.
But as the data is array based, but the size changes and varies.
Then i need to search for parts of string and want to get everyhting after the
part til next comma.
{"id":2988001,"teatiseNr":"50000099027","mkood":74,
Now here is the string.
I would only like to have everything after {"id":
til the first comma.
So my output would be 2988001
Why i need the search criteria is because some times there are more variables and that messes up the order.
Right now im using simple
$pieces = explode(",", $page);
And then just delete the rest with
str_replace('{"id":','',$pieces[0]);
There must be more elegant way to make this work.
this is a json string, so you can simply do:
$data = json_decode($string);
echo $data->id;
If it is array based then alistaircol, matei, and neil are right you should use something like
$data = json_decode($page);
$id = $data->id
Let's say for some reason the response actually not JSON and the order of the item with id is variable then something like this could work too
$no_braces = str_ireplace('{','',$page);
$no_quotes = str_ireplace('"','',$no_braces);
$items = explode(",",$no_quotes);
function getID($items){
foreach($items as $item){
$parts = explode($item, ':');
$key = $parts[0];
if($key === 'id'){
return $parts[1];
}
}
return null;
}

How to check if certain value exist in csv file with PHP

I've a field in my database which has csv values, if I get the value in a variable it looks like
$data = "dell, dell7, jhon5, doe4";
//these are user id's
I need to check if a certain id is already in this variable.
I used explode() with foreach() and it worked well. But, I need to do this in several times and my code become messy.
Is there any other way?
I'm using Laravel(Lumen)
function checkId($id){
$data = "dell, dell7, jhon5, doe4";
$array = explode(",", $data);
return in_array($id, $array);
}
Another alternative will be preg_match(), like this -
$data = "dell, dell7, jhon5, doe4";
$search = 'dell';
if(preg_match("/\b".$search."\b/i", $data)){
echo 'found';
}
I am not sure about this solution. But this strikes in my mind when I saw your question.

foreach () Error

I'm getting the following warning when running this script:
Warning: Invalid argument supplied for foreach()
This is the script:
$values = array();
foreach ($_POST['rights'] as $right_id)
{
$values[] = '(' . $id . ', ' . $right_id . ')';
}
$_POST['rights']/$id are integers. In this case it was $_POST['rights'] = 1,2,3,4,5; $id = 2.
The strange part is that on a different page with the same kind of input it gives no errors.
The question: What is wrong with it?
check $_POST['rights']
var_dump($_POST['rights']);
I think $_POST['rights'] is not an array.
foreach must take an array, you're passing it an integer. You can't iterate over an integer.
A wise move might be to check whatever you're about to iterate over is indeed an array:
if(is_array($_POST['rights'])){
foreach($_POST['rights'] as $value){
//Whatever you want to do with each $value
}
}
else {
//Let the user know it's hit the fan…
throw new Exception('Help, I\'m not an array :(')
}
PHP docs for arrays: http://php.net/manual/en/language.types.array.php
PHP docs for foreach: http://php.net/manual/en/control-structures.foreach.php
As per your statement $_POST['rights'] is not an array.
It is probably a simple string having 1,2,3,4
You need to convert it into an array with explode function.
e.g
$_POST['rights'] = explode(",", $_POST['rights']);
Then your for loop will work.
The passed array $_POST['rights'] probably is empty.
EDIT:
Like Mark Baker said an empty array is fine. You should go with the other answers.

Breaking a file with explode

Today I figured out how to explode a file into fragments. I got it done with the following piece of code.
<?php
$file = file('url here');
foreach ($file as $files)
{
list($example) = explode(',', $file);
}
?>
But when I echo the $example out, I am just getting a text saying "Array" as the output. The text file which I inputted looks like the following
1,2,3,4,5
I expect the output to be like the following
1
2
3
4
5
So is it possible. If yes please help me out
That is because $example is an array. That is why "Array" is returned. Print it like this instead:
foreach($example as $item) echo $item,"\n";
Use <br> after each item for HTML or PHP_EOL for text files
foreach ($example as $item)
{
echo "$item<br>".PHP_EOL;
}
$example will be an array, so you need to use print_r() or specify a index to echo:
echo $example[1];
Ideally, to print all the elements, you could simply do another loop:
foreach($example as $element){echo $element."<br>";}
I think you have got two issues here, and you should solve one after the other. This is one I could spot:
Instead of:
list($example) = explode(',', $file);
Try with:
$example = explode(',', $file);
Also take care, that if you have multiple lines, you'll overwrite $example, so you might want to output it inside the foreach loop already.

array_unshift() with empty array

I want to add an element to the beginning of an array, but this array might be empty sometimes. I've tried using array_unshift() but it doesn't seem to like empty arrays... should I simply check for the empty array and append the element manually, or does array_unshift() not mind empty arrays but I'm just being a klutz?
Here is my code at the moment:
$sids = array();
$sids = explode(",", $sid['sids']);
array_unshift($sids, session_id());
The contents of the $sids array are taken from a database and are comma separated values.
Thanks,
James
EDIT
I've managed to fix this now - sorry everyone!
Here's the updated code:
$sids = array();
if(!empty($row['sids']))
{
$sids = explode(",", $row['sids']);
}
array_unshift($sids, session_id());
If $sid['sids'] is empty, explode will return FALSE
Then $sids will be equal to FALSE
and the subsequent call to array_unshift will fail.
You should probably make sure $sids is an array before calling array_unshift.
Here's a way to do it:
if(!empty($sid['sids']))
$sids = explode(",", $sid['sids']);
else
$sids = array();
array_unshift($sids, session_id());
First off, your first line of code is pointless; explode always returns a value, whether it be an array or FALSE. You're guaranteed to overwrite that value once you call explode.
Secondly, your code should work. One minor edit I'd make is this:
<?php
$sids = array();
$sids = explode(",", $sid['sids']);
if(is_array($sids))
array_unshift($sids, session_id());
?>
Because (even though your code says otherwise, and that the PHP documentation says otherwise), explode may not always return an array.
Another piece of information that may be useful is whether or not there was any error being reported, and, if so, what the error was.
Best of luck!
array_unshift() accepts the array parameter by reference. This means it must actually be a variable, not an expression like array(). It also means it will modify the variable you pass, not return a new array with the element added. Here's an example to illustrate this:
$array = array();
array_unshift($array, 42);
var_dump($array); // Array now has one element, 42
$sids = explode(",", $sid['sids']);
if (!is_array($sids)) {
$sids = array();
}
array_unshift($sids, session_id());

Categories