从php中的数组的每个元素中删除字符串的一部分


Remove a part of string from each element of an array in php

我有一个数组

["item1","item2","item3"]

我想要一个["1","2","3"]的数组

如何在php

中获得

您需要这个

$arr = ["item1","item2","item3"];
for ($i = 0; $i < sizeof($arr); $i++) {
    // replace "item" with ""
    $arr[$i] = str_replace("item","",$arr[$i]);
}
<?php
$given_array = ["item1","item2","item3"];
$new_array = array();
foreach ($given_array as $arr) {
    $new_array[] = intval(preg_replace('/[^0-9]+/', '', $arr), 10);
}
echo '<pre>';
print_r($new_array);
?>

1)只需使用

$res = str_replace('item', '', $array);

输出$res

Array
(
  [0] => 1
  [1] => 2
  [2] => 3
)

2) 使用array_map()

$array = array_map(
  function($str) {
    return str_replace('item', '', $str);
  },
  $array
);