Using preg_replace on an array

前端 未结 3 434
孤独总比滥情好
孤独总比滥情好 2021-01-13 07:55

I have a relatively large array of elements which I want to search for a string and replace any matches. I\'m currently trying to do this using preg_replace and

相关标签:
3条回答
  • 2021-01-13 08:43

    your $array contains some further arrays. preg_replace works fine with arrays of strings, but not with arrays of arrays [of arrays...] of strings.

    0 讨论(0)
  • 2021-01-13 08:53

    Your value does not sit in the array as a simple element but as a subset right? Like so?

    array (
      array ('id' => 45, 'name' => 'peter', 'whatyouarelookingfor' => '5F'),
      array ('id' => 87, 'name' => 'susan', 'whatyouarelookingfor' => '8C'),
      array ('id' => 92, 'name' => 'frank', 'whatyouarelookingfor' => '9R')
    )
    

    if so:

    <?php
    
    foreach ($array as $key => $value) {
      $array[$key]['whatyouarelookingfor'] =  
        preg_replace("/\d?\dIPT\.\w/", "IPT", $value['whatyouarelookingfor']);
    }
    

    Or if more elements have this, just go broader:

    <?php
    
    foreach ($array as $key => $value) {
      $array[$key] =  
        preg_replace("/\d?\dIPT\.\w/", "IPT", $value);
    }
    
    0 讨论(0)
  • 2021-01-13 08:58

    preg_replace doesn't modify in place. To permanently modify $array, you simply need to assign the result of preg_replace to it:

    $array = preg_replace("/\d{1,2}IPT\.\w/", "IPT", $array);
    

    works for me.

    $array = array('00IPT.A', '0IPT.A');
    $array = preg_replace("/\d{1,2}IPT\.\w/", "IPT", $array);
    var_dump($array);
    // output: array(2) { [0]=> string(3) "IPT" [1]=> string(3) "IPT" }
    

    Note: the \d{1,2} means one or two digits.

    If you want to do this to a two-dimensional array, you need to loop through the first dimension:

    $array = array( array('00IPT.A', 'notmatch'), array('neither', '0IPT.A') );    
    foreach ($array as &$row) {
        $row = preg_replace("/\d{1,2}IPT\.\w/", "IPT", $row);
    }
    var_dump($array);
    

    output:

    array(2) { 
        [0]=> array(2) { 
            [0]=> string(3) "IPT" 
            [1]=> string(8) "notmatch" 
        } 
        [1]=> &array(2) { 
            [0]=> string(7) "neither" 
            [1]=> string(3) "IPT" 
        } 
    }
    

    Note that you have to loop through each row by reference (&$row) otherwise the original array will not be modified.

    0 讨论(0)
提交回复
热议问题