【问题标题】:Shortening full name down so Surname is only first letter缩短全名,所以姓氏只是第一个字母
【发布时间】:2012-07-13 02:40:50
【问题描述】:

在阅读了一些已经提出的问题并检查了其他一些网站之后,我仍然没有进一步寻找一种简单的方法来取全名,比如说“Jake Whiteman”并将其修剪下来以便显示在网页上显示为“Jake W”。显然它周围没有语音标记,所以那里没有任何混乱。

有人知道怎么做吗?我敢肯定这可能只是找到空白然后修剪姓氏的问题,我似乎无法找到一种方法。

提前致谢!

【问题讨论】:

标签: php string trim


【解决方案1】:
$names = explode( " ", $name );
echo $names[0]." ".$names[1][0];

【讨论】:

  • 可能无关紧要,但 Shamus O'Callaghan 呢?
  • 这仍然有效,虽然它看起来很尴尬,但在我看来,这更像是一个边缘情况,这取决于 OP 是否需要检查它。
  • @Josh Irish 嗯? :D
【解决方案2】:

您可以使用此代码。这适用于 3 个单词的名称,假设第二个单词是中间名,只有姓氏会被截断。

<?php

$name = "Jake Awesome Whiteman";
$separate = explode(" ", $name);
$last = array_pop($separate);

echo implode(' ', $separate)." ".$last[0].".";

?>

【讨论】:

    【解决方案3】:

    假设它们的格式始终为“[Other Names] LastName”,因此最后一个单词始终是姓氏,您可以通过 php 函数 explode() 将其通过分隔符 [space] 拆分为标记( http://php.net/manual/en/function.explode.php)

    // Given
    $name = "Jake Whiteman";
    
    // Process
    // Tokenize, getting separate names
    $names = explode(' ', $name);
    // Pop last name into variable $last_name, keep remaining names in $names
    $last_name = array_pop($names);
    // Get last initial
    $last_initial = $last_name[0];
    
    // Put first names back together
    $beginning = implode(' ', $names);
    $full_name = $beginning.' '.$last_initial.'.';
    

    你可以把这一切放在一个函数中:

    function nameWithLastInitial($name) {
        $names = explode(' ', $name);
        $last_name = array_pop($names);
        $last_initial = $last_name[0];
        return implode(' ', $names).' '.$last_initial.'.';
    }
    $name = "Jake Whiteman";
    echo nameWithLastInitial($name); // Should print 'Jake W.'
    

    【讨论】:

    • 这比我的版本强大得多。
    • 仍然对字符串格式和数组长度做了很多假设:)。鲁棒性只在需要时才有用。如果您可以假设一个更简单的解决方案,那就去做吧,无论如何它通常会有更好的性能。
    【解决方案4】:
    $name = "Jake Whiteman";
    $names = explode(' ', $name); //$names[0] = "Jake", $names[1] = "Whiteman"
    echo $names[0]." ".substr($names[1], 0,1).".";
    

    【讨论】:

      【解决方案5】:

      当只有名字和用户输入多个名字时这会很有帮助

      <!DOCTYPE html>
      <html>
      <head>
      <title></title>
      </head>
      <body>
      <?php
      
      $userName = "Jakeds hfg gsd";
      if(preg_match('/\s/',$userName)) {
      $separate = explode(" ", $userName);
      $last = array_pop($separate);
      $first = mb_strimwidth($separate[0], 0 , 15);
      echo $first." ".$last[0].".";
      } else {
      $first = mb_strimwidth($userName, 0 , 15);
      echo $first;
      }
      
      //echo $first." ".$last[0].".";
      
      ?>
      </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 2014-08-21
        • 1970-01-01
        • 2016-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多