【问题标题】:How to remove the last word and the last letter if is an 'n' of the first word of a text using php如何使用php删除最后一个单词和最后一个字母如果是文本第一个单词的'n'
【发布时间】:2019-11-16 04:48:21
【问题描述】:

我正在尝试使用 php.ini 删除文本的第一个单词的最后一个单词和最后一个字母(如果是'n')。

这是一个简单的名字和姓氏的例子:

John Doe 必须变成 Joh

现在我使用下面的代码完全删除姓氏。

<?php 
$firstname = stripos('John Doe', ' ');
echo substr('John Doe', 0, $firstname); 
?>

结果是约翰

如何修改我的代码,以便名称中的最后一个字母仅在 'n' 时才会被删除?

【问题讨论】:

    标签: php


    【解决方案1】:

    试试这个:

    <?php 
        $firstname = stripos('John Doe', ' ');
        $firstname = substr('John Doe', 0, $firstname); 
        if (substr($firstname, -1) == 'n') {
            echo substr($firstname, 0, -1);
        };
    ?>
    

    【讨论】:

      【解决方案2】:

      这应该可行,假设您总是有一个至少两个部分的名称。不然会生气的。非常奇怪的用例。

      $name = "John Doe";
      
      $parts = explode(' ', $name);
      if(strpos($parts[0], 'n') == strlen($parts[0])-1){
          echo substr($parts[0], 0, strlen($parts[0])-1); // Joh
      }
      

      【讨论】:

        猜你喜欢
        • 2021-03-18
        • 2017-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-03
        • 1970-01-01
        相关资源
        最近更新 更多