Using preg_replace for an array

I have a relatively large array of elements that I want to find a string and replace any matches. I am currently trying to do this using preg_replaceregular expressions:

preg_replace("/\d?\dIPT\.\w/", "IPT", $array);

I want to get all the values ​​that match 00IPT.Aor 0IPT.A(where 0represents any numeric character and Arepresents any letter), and replace them with IPT. However, I get notifications about the conversion of the array to string. Is there any way to force preg_replacean array to accept a data source? If not, is there any other way to achieve this?

The documentation says that it preg_replaceshould accept array sources - that’s why I ask.

A string or array with strings for searching and replacing. If the topic is an array, then search and replace are performed for each topic entry, and the return value is also an array.

An array is multidimensional if that helps (has multiple arrays in the same main array).

+5
source share
3 answers

preg_replacedoes not change in place. To permanently change $array, you just need to assign it the result preg_replace:

$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: \d{1,2}means one or two digits.

If you want to do this with a two-dimensional array, you need to loop in 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" 
    } 
}

, (&$row), .

+9

$array . preg_replace , [...] .

+1

Your value is not in the array as a simple element, but as a subset to the right? Like this?

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 wider:

<?php

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

Source: https://habr.com/ru/post/1532785/


All Articles