简体   繁体   English

大写字符串的最后一个字母

[英]Capitalize last letter of a string

How can I capitalize only the last letter of a string. 如何将字符串的最后一个字母大写。

For example: 例如:

hello

becomes: 变为:

hellO

Convoluted but fun: 令人困惑但有趣:

echo strrev(ucfirst(strrev("hello")));

Demo: http://ideone.com/7QK5B 演示: http//ideone.com/7QK5B

as a function: 作为一个功能:

function uclast($str) {
    return strrev(ucfirst(strrev($str)));
}

When $s is your string ( Demo ): $s是你的字符串( Demo )时:

$s[$l=strlen($s)-1] = strtoupper($s[$l]);

Or in form of a function: 或者以函数的形式:

function uclast($s)
{
  $l=strlen($s)-1;
  $s[$l] = strtoupper($s[$l]);
  return $s;
}

And for your extended needs to have everything lower-case except the last character explicitly upper-case: 并且为了您的扩展需求,除了最后一个字符明确大写之外,所有内容都是小写的:

function uclast($s)
{
  $l=strlen($s)-1;
  $s = strtolower($s);
  $s[$l] = strtoupper($s[$l]);
  return $s;
}

There are two parts to this. 这有两个部分。 First, you need to know how to get parts of strings. 首先,您需要知道如何获取字符串的一部分。 For that, you need the substr() function. 为此,您需要substr()函数。

Next, there is a function for capitalizing a string called strtotupper() . 接下来,有一个函数用于大写一个名为strtotupper()的字符串。

$thestring="Testing testing 3 2 1. aaaa";
echo substr($thestring, 0, strlen($thestring)-2) . strtoupper(substr($thestring, -1));

Lowercase / uppercase / mixed character case for everything following can be used 可以使用以下所有内容的小写/大写/混合字符大小写

<?php
    $word = "HELLO";

    //or

    $word = "hello";

    //or

    $word = "HeLLo";

    $word = strrev(ucfirst(strrev(strtolower($word))));

    echo $word;
?>

Output for all words 所有单词的输出

hellO
$string = 'ana-nd';

echo str_replace(substr($string, -3), strtoupper('_'.substr($string, -2)), $string);

// Output: ana_ND


$string = 'anand';

echo str_replace(substr($string, -2), strtoupper(substr($string, -2)), $string);

// Output: anaND

Here's an algorithm: 这是一个算法:

  1. Split the string s = xyz where x is the part of
     the string before the last letter, y is the last
     letter, and z is the part of the string that comes
     after the last letter.
  2. Compute y = Y, where Y is the upper-case equivalent
     of y.
  3. Emit S = xYz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM