4

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).

Sami
  • 69
  • 8
  • 1
    Possible duplicate of [PHP Arrays - Adding a String to all Values](http://stackoverflow.com/questions/4535846/php-arrays-adding-a-string-to-all-values) – Sahil Gulati Mar 09 '17 at 09:48
  • @SahilGulati: Actually, this OP regex solution is taken from that very post. I think OP is interested in the regex way of adding suffixes to the PHP array which is more appropriate if there are additional pattern requirements (not sure if OP revealed all the details of the real-life problem). – Wiktor Stribiżew Mar 09 '17 at 09:50
  • @SahilGulati: I need just Regex. Thanks to Wiktor Stribiżew. – Sami Mar 09 '17 at 10:02

2 Answers2

5

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • I need to add prefix at start and end of value as well, then how this can be done via `preg_filter`? – Muhammad Hassaan Jan 24 '19 at 14:35
  • 1
    @Hassaan I think you want to use `preg_replace` for this. Like `$arr = preg_replace('/^.*$/', 'PREF_$0_SUFF', $arr);`. Or `$arr = array_map(function ($s) {return 'prefix_' . $s . '_suffix';}, $arr)` – Wiktor Stribiżew Jan 24 '19 at 15:24
0

additional approach using array_map

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

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

print_r($array);
hassan
  • 7,812
  • 2
  • 25
  • 36
  • This is actually part of my answer. Moreover, I think OP is interested in the *regex* way of solving the issue, otherwise, the [PHP Arrays - Adding a String to all Values](http://stackoverflow.com/questions/4535846/php-arrays-adding-a-string-to-all-values) post is enough. – Wiktor Stribiżew Mar 09 '17 at 09:50
  • I've saw your update after posting my answer , sorry – hassan Mar 09 '17 at 09:51