簡體   English   中英

PHP替換字符串不起作用

[英]Php replace string not working

我正在嘗試從文件中替換特定的字符串,但我無法這樣做。這是我的PHP代碼:

<?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{


          }


 ?>

這是文件中存在的json:

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

],
"B":[

{
"name":"Beyonce"
}

]

}

編輯:

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

我要替換文件的內容。 在這里,我試圖替換Array A中的內容。 這是我正在嘗試使用的以上代碼,用新的String替換Array A的內容。 但是我仍然無法保持原樣。我沒有收到任何錯誤。 我能知道我要去哪里了嗎?

從我看到的地方,您的代碼有一些問題。 讓我們回顧一下您要嘗試執行的操作:

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

據我了解,您想使用$str ,在$contactList搜索該特定字符串,然后將該字符串的所有實例替換為$strArr 我注意到的第一個問題是您沒有正確使用str_replace() 您需要使用通配符: %來定義$str的限制。 例如:

//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

因此,在您的情況下,您的代碼應如下所示:

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

但是 ,您的代碼中還有另一個問題。 我注意到,里面的串$str不正是里面的字符串匹配$contactList因為你有額外的內部空間$contactList 因此,您還必須選擇以下兩項之一(以及先前的代碼更正:

  • 無論哪種方式, $contactList確保$contactList$str里面的字符串完全相同。

  • 或將regexpreg_replace()一起使用,以創建更高級的搜索,盡管這有點復雜,並且如果您不知道regex將需要一些教程時間:)。


編輯:我只是注意到$contactList上使用的json_decode 如果將json_decode放在str_replace函數之后並使用我的代碼,則$contactList將不再具有空格,並且該函數應能正常工作:)

您可以通過以下方式更輕松地完成此操作:

$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));
}

如果不確定函數在PHP中的作用(如json_decode ),則可以簡單地使用var_dump查看變量包含的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM