Search and replace inside an associative array

后端 未结 10 1853
没有蜡笔的小新
没有蜡笔的小新 2021-01-20 22:14

I need to search and replace inside an associative array.

ex:

$user = \"user1\"; // I\'ve updated this

$myarray = array(\"user1\" => \"search1\",         


        
相关标签:
10条回答
  • 2021-01-20 22:47

    Following on from Joseph's answer, using preg_replace may enable you to use the code in other situations:

    function pregReplaceInArray($pattern,$replacement,$array) {
        foreach ($array as $key => $value) {
            $array[$key] = preg_replace($pattern,$replacement,$value);
        }   
        return $array;
    }
    
    0 讨论(0)
  • 2021-01-20 22:53
    $originalArray = array( "user1" => "search1" , "user2" => "search2" );
    $pattern = 'search1';
    $replace = 'search4';
    
    $replacedArray = preg_replace( '/'.$pattern.'/' , $replace , $originalArray );
    

    Fixes the risk mentioned in comment in response to this solution

    0 讨论(0)
  • 2021-01-20 22:53

    Using str_replace should work:

    $myarray = array("user1" => "search1", "user2" => "search2" ) ;
    
    $newArray = str_replace('search1', 'search4', $myarray);
    
    0 讨论(0)
  • 2021-01-20 22:54

    if you want for particular key then you just add condition for key in previous ans like.

    $user = "user1";
    $myarray = array("user1" => "search1", "user2" => "search2" );
    
    foreach($myarray as $key => $val)
    {
        if ($val == 'search1' && $key == $user) $myarray[$key] = 'search4';
    }
    
    0 讨论(0)
提交回复
热议问题