在数组上使用preg_replace [英] Using preg_replace on an array
问题描述
我有一个较大的元素数组,我想搜索一个字符串并替换所有匹配项.我目前正在尝试使用preg_replace
和正则表达式:
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 regular expressions:
preg_replace("/\d?\dIPT\.\w/", "IPT", $array);
我想获取所有与00IPT.A
或0IPT.A
匹配的值(其中0
代表任何数字字符,A
代表任何字母),并将它们替换为IPT
.但是,我收到了数组到字符串转换的通知.有什么办法让preg_replace
接受数组数据源?如果没有,我还有其他方法可以实现吗?
I want to get all values which match either 00IPT.A
or 0IPT.A
(with 0
representing any numerical character and A
representing any letter) and replace them with IPT
. However, I'm getting array to string conversion notices. Is there any way to get preg_replace
to accept an array data source? If not, is there any other way I could achieve this?
文档说preg_replace
应该能够接受数组源-这就是我要问的原因.
The documentation says that preg_replace
should be able to accept array sources — this is the reason I'm asking.
字符串或包含要搜索和替换的字符串的数组. 如果subject是一个数组,那么将对subject的每个条目执行搜索和替换,并且返回值也将是一个数组.
The string or an array with strings to search and replace. If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well.
如果有帮助的话,该数组是多维的(在一个主数组下有多个数组).
推荐答案
preg_replace
未就地修改.要永久修改$array
,您只需要将preg_replace
的结果分配给它:
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);
为我工作.
$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" }
注意:\d{1,2}
表示一位或两位数字.
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);
输出:
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
),否则原始数组将不会被修改.
Note that you have to loop through each row by reference (&$row
) otherwise the original array will not be modified.
这篇关于在数组上使用preg_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!