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"];
To this:
$array = ["a_M", "b_M", "c_M", "d_M", "f_M"];
I can do it with foreach
, but need a regular expresion (Just Regex).
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);
See the PHP demo
A non-regex way is to use array_map
like this:
$suffixed_array = array_map(function ($s) {return $s . '_M';}, $array);
See this PHP demo.
additional approach using array_map
$array = ["a", "b", "c", "d", "f"];
$array = array_map(function($k) {
return $k . '_M';
}, $array);
print_r($array);