【问题标题】:PHP Format Name using Array e.g. John Smith to John S使用数组的 PHP 格式名称,例如约翰史密斯到约翰 S
【发布时间】:2022-01-21 02:44:52
【问题描述】:

$data['full_name'] 存储全名,例如约翰·史密斯

目前我正在使用

$data['full_name'] = strtok($data['full_name'], " ");

这将为我转换名字 - 例如约翰

我还想包括第二个名字 - 例如约翰·S

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    我会在这里使用正则表达式替换:

    $input = "John Michael Smith";
    $output = preg_replace("/(?<=\s)(\w)\w*/", "$1", $input);
    echo $output;  // John M S
    

    我使用了一个正则表达式模式,它将针对名字中除名字之外的所有单词,并仅替换为第一个字母。此处使用的正则表达式模式表示匹配:

    (?<=\s)  assert that a space precedes (excludes the first name)
    (\w)     match and capture the first letter
    \w*      then consume the rest of the name, without matching
    

    我们替换为$1,它只是名称组件的第一个字母。

    【讨论】:

      【解决方案2】:

      使用这个代码sn-p

      <?php
      
      $input = "John Smith";
      $name = explode(" ", $input);
      $formatted = "";
      foreach ($name as $key => $value)
      {
          // code...
          if ($key == 0) {
              $formatted .= $value;
          } else {
              $formatted .= ' ' . substr($value, 0, 1);
          }
      }
      
      echo $formatted;
      

      【讨论】:

      • 也许添加一些 cmets 来说明您的解决方案为何以及如何解决问题。旁注,我正在为你格式化你的代码。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      相关资源
      最近更新 更多