1

I am trying to replace a particular string from a file but I am not able to.This is my php code:

<?php 

  session_start();

          $name = $_GET["Username"];
          $status = $_GET["Status"];

          $username = "jois";



          if($status == "Following"){
          $filename = $username."/contacts.txt";
         $contactList =  file_get_contents($filename);

              $object =    json_decode($contactList,TRUE);  

               $array = $object["A"];

            $str = json_encode($array);

            $new =   array('name' => 'Sumanth' );

              array_push($array,$new);

    $strArr =  json_encode($array);

            echo "str: ".$str."\n";
            echo "strArr: ".$strArr."\n";


        if( str_replace($str,   $strArr, $contactList)){
            echo    str_replace($str,   $strArr, $contactList);
        }
        else{
            echo "couldnt find the match";
        }

          }
          else{


          }


 ?>

This is the json present in the file:

  {
"A":[
{
"name": "Aaron Paul"
}

],
"B":[

{
"name":"Beyonce"
}

]

}

EDIT:

$str= [{"name":"Aaron Paul"}]
 $strArr= [{"name":"Aaron Paul"},{"name":"Sumanth"}]
  $contactList={ "A":[ { "name": "Aaron Paul" } ], "B":[ { "name":"Beyonce" } ] }

I want to replace the contents of the file . Here I am trying to replace contents in the Array A. and This is the above code I am trying o use to replace contents of Array A with a new String. But I am not able to it still remains the same.I am not getting any error. Can I know where I am going wrong?

7
  • can i use the json file for the solution??? Commented May 26, 2016 at 7:41
  • Show us the before and after of the json file with your current code, and then show us how you want the "after" to look like Commented May 26, 2016 at 7:41
  • @FrayneKonok Yes you can Commented May 26, 2016 at 7:42
  • @Webeng I am not actually changing the file contents in this code but i will edit and upload the the string values Commented May 26, 2016 at 7:43
  • See this: https://3v4l.org/4feTG Commented May 26, 2016 at 7:47

2 Answers 2

2

You have a few problems with your code from where I see it. Lets review what you are tryoing to do:

$str= [{"name":"Aaron Paul"}]
 $strArr= [{"name":"Aaron Paul"},{"name":"Sumanth"}]
  $contactList={ "A":[ { "name": "Aaron Paul" } ], "B":[ { "name":"Beyonce" } ] }

From my understanding, you want to take $str, search for that specific string inside $contactList, and then replace all instances of that string with $strArr. The first problem I noticed is that you did not use str_replace() correctly. You need to use the wildcard character: % to define the limits of $str. For example:

//if you had the following string:
$string = 'abcdeafg';
//and you wanted to replace all the instances
//of 'a' with 'z'
$str1 = 'a';
$str2 = 'z';
//you would then need to use '%' as follows:
$result = str_replace("%{$str1}%", "{str2}", $string);
echo $result;//output: zbcdezfg

So in your case, your code should look like this:

$result = str_replace("%{$str}%",  "{$strArr}", $contactList);

HOWEVER, you have another problem in your code. I am noticing that the string inside $str does not exactly match the string inside $contactList because you have additional spaces inside $contactList. So you would also have to 2 one of the following things (along with the previous code correction:

  • Either somehow make sure $contactList has the exact same string as $str inside it.

  • Or use regex with preg_replace() to create a more advanced search, though that is a bit more complicated and if you don't know regex will demand some tutorial time :).


Edited: I just noticed the json_decode being used on $contactList. If you place json_decode after the str_replace function and use my code, then $contactList will no longer have the spaces and the function should work fine :)

Sign up to request clarification or add additional context in comments.

6 Comments

I am working on it Give me some time I will let you know
I really don't understand why you spent so much time explaining something which is really wrong.. json_decode function returns an object/array which can be easily modified. Why should I complicate the code with string replacements when I can easily use array functions?
@MateiMihai Please go throught question again
@Webeng Thankyou I used preg_replace to remove all the white spaces! and now it's working. It was whitespaces ! The Culprit thankyou
@Webeng % dint help me out
|
0

You can do it more easily as:

$username = "jois";

if ($status == "Following") {
    $filename = $username . '/contacts.txt';

    $contacts = json_decode(file_get_contents($filename), true);  

    $contacts['A'] = array('name' => 'Sumanth');

    file_put_contents($filename, json_encode($contacts));
}

If you're not sure what a function does in PHP (like json_decode) you can simply use var_dump to see what the variables contains.

5 Comments

Actually I want keep the old contents also ! I just want add the new element to A array with removing any elements
You want to remove or you don't want to remove the other elements of A? Right now the code simply adds a new element to the array.. as I suppose you want
@Jois did you tested the solution I gave? is there something wrong?
Yea i did I am not getting the solution ! I am sorry
and the solution is? let me know what do you expect to have in the file at the end..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.