正则表达式向PHP数组的每个项目添加后缀 [英] Regex to Add a postfix to each item of a PHP array

查看:112
本文介绍了正则表达式向PHP数组的每个项目添加后缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP字符串数组,我想用一个字符后缀。在正则表达式下面添加每个数组元素的前缀:

I have a PHP array of strings, which I would like to postfix with a character. below regular expression to add something prefix of each array elements:

$prefixed_array = preg_filter('/^/', 'prefix_', $array);

但是,我需要添加后缀。

But, I need add postfix.

基本上,我想从这里开始:

Essentially I would like to go from this:

$array = ["a", "b", "c", "d", "f"];

到此:

$array = ["a_M", "b_M", "c_M", "d_M", "f_M"];

我可以用 foreach 做到这一点,但是需要常规的表达式(正则表达式)。

I can do it with foreach, but need a regular expresion (Just Regex).

推荐答案

如果要使用 preg_filter 为此使用正则表达式,将 ^ 替换为 $ (字符串的结尾)(或 \z -字符串的结尾):

If you want to use preg_filter with a regex for this, replace ^ with $ (the end of string) (or \z - the very end of the string):

$array = ["a", "b", "c", "d", "f"];
$suffixed_array = preg_filter('/$/', '_M', $array);
print_r($suffixed_array);

请参见 PHP演示

一种非正则表达式的方法是使用 array_map 像这样:

A non-regex way is to use array_map like this:

$suffixed_array = array_map(function ($s) {return $s . '_M';}, $array);

请参见此PHP演示

这篇关于正则表达式向PHP数组的每个项目添加后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆