将名称数组的格式从 "last, first" 更改为 "first last"

Change format of an array of names from "last, first" to "first last"

我需要反转名称字符串数组中名字和姓氏的方向。

$names = [
    "barira, stefan",
    "cikka, maria",
    "luppo, martin ",
    "bill, sebastian"
];

输出必须是这样的:

Array ( [0] => stefan, barira 
        [1] => maria, cikka 
        [2] => martin, luppo  
        [3] => sebastian, bill ) 

我已经接近这段代码了,但我希望它像上面的输出一样:

$names = [
    "barira, stefan",
    "cikka, maria",
    "luppo, martin ",
    "bill, sebastian"
];
 
for ($i = 0; $i < count($names); $i++) {
    $words = $names[$i];
    $string = explode(' ', $words);
    $string = array_reverse($string);
    $reverse = implode(' ', $string);
    print_r($reverse);
}

这就是我要做的

$names = ["barira, stefan",
      "cikka, maria",
      "luppo, martin ",
      "bill, sebastian"];

//note the & pass by reference, this way we don't even need a new array
foreach($names as &$name)
  $name= implode(' ', array_reverse(array_filter(array_map('trim', explode(',', $name)))));

print_r($names);

输出

Array
(
    [0] => stefan barira
    [1] => maria cikka
    [2] => martin luppo
    [3] => sebastian bill
)

Sandbox

如果你愿意,我可以解释这些函数的作用...

如果你绝对想要 , 回到那里,我认为这是个坏主意,你可以改变这个:

 $name = implode(', ', ...... );

From a comment I made: it's probably a bad idea keeping that , in there. How will know it's been "reversed". Also the standard way is First Middle Last OR Last, First Middle

PS。您可以添加 ucwords() 以大写名称的第一个字母。只需将它包裹在内爆周围,或者在它爆炸之前包裹起来

这里有两种有趣的方式。映射每个元素,反向分解和连接:

$result = array_map(function($v) {
                        $a = explode(',', $v);
                        return trim($a[1]).', '.trim($a[0]);
                    }, $names);

Example 1

或者,捕获这两个名称并将它们替换为相反的:

$result = preg_replace('/(\w+),\s+(\w+)/', ', ', $names);

Example 2

  • 匹配单词字符 \w 一次或多次 + 并在第 1 组中捕获 ()
  • 后跟一个 , 然后 space \s 一次或多次 +
  • 后跟单词字符 \w 一次或多次 + 并在第 2 组中捕获 ()
  • 替换为捕获组 2 a , 和 a space 以及捕获组 1 ,

一次 preg_replace() 调用就足以可靠地 trim 不需要的字符并将姓氏移到名字之后。

代码:(Demo)

$names = [
    " barira, stefan",
    "cikka , maria",
    "luppo, martin ",
    "bill,sebastian",
    "van gogh , mary jane",
];

var_export(
    preg_replace('~^\s*([^,]+?)\s*,\s*(.*?)\s*$~', ' ', $names)
);

输出:

array (
  0 => 'stefan barira',
  1 => 'maria cikka',
  2 => 'martin luppo',
  3 => 'sebastian bill',
  4 => 'mary jane van gogh',
)

模式将:

  1. 匹配字符串开头的前导空白字符
  2. 延迟捕获非逗号字符
  3. 匹配逗号前的空白字符
  4. 匹配逗号
  5. 匹配逗号后的空白字符
  6. 懒惰地捕获一个或多个任意字符
  7. 匹配字符串末尾的空白字符