更流畅的方式来做一个多str_replace


slicker way to do a mulitple str_replace

使用str_replace而不是以下内容更改多个项目的最佳方法是什么:

$dataMeta = str_replace(['fooboy_','foogirl_','foonut_'],['','',''],$source);

例如。。。。

更改: fooboy_1234 | foogirl_5678 | foonut_0909

转至: 1234 | 5678 | 0909

改用preg_replace

$string = 'foo_3456';
echo preg_replace('/[a-z]+_('d+)/i', '${1}', $string);

现场示例在这里

因此,使用这种简单的方法,您可能会将其应用于字符串数组,例如使用 array_map

函数
$strings = ['foo_1234', 'bar_3456', 'foo_5678', 'bar_7890'];
$strings = array_map(
    function($string){
        return preg_replace('/[a-z]+_('d+)/i', '${1}', $string);
    },
    $strings
);
var_dump($strings);

现场示例在这里