【问题标题】:Another Capitalization question另一个大小写问题
【发布时间】:2011-08-01 08:39:52
【问题描述】:

这就是我想要做的。我有页面的标题。我正在尝试将每个字符串中第一个单词的最后一个字母大写

例子:

哎哟

你好吗

我可以用一个词让它工作,但如果有多个词,我不知道该怎么做。任何帮助都会很棒!

非常感谢!

【问题讨论】:

  • 为什么,为什么,这是正常的语法。
  • 尝试向我们展示您当前拥有的代码。

标签: php capitalization


【解决方案1】:

试试这个

<?php

    $title                  = "Hello World";
    list($firstword, $rest) = explode(" ", $title, 2);
    $firstword              = strrev(ucfirst(strrev($firstword)));
    $title                  = $firstword . " " . $rest;

    print $title;

如果您想了解有关任何功能的更多信息,请参阅explodestrrevlistucfirst

【讨论】:

  • 他们很快就能获得声誉,凯西。
  • 我们当然是。但我们也确实有帮助他人的良好意愿。声誉是帮助他人,而不是快速。如果您以错误的答案快速回复,您将失去声誉,而不是获得收益。因此,首先是信息共享和帮助,其次是声誉。 :)
【解决方案2】:

由于您知道如何处理 1 个单词,因此您只需要获取第一个单词,然后输入您的算法。

  1. 试试preg_replace_callback"/^(\w+)/"
  2. 替换回调方法中的最后一个字符。

preg_replace_callback:http://php.net/manual/en/function.preg-replace-callback.php

更新 - 工作代码:

$string = "This is a test";
$string = preg_replace_callback(
        '/^(\w+)/',
        create_function(
            '$matches',
            'return yourUCLastAlgorithm($matches[0]);'
        ),
        $string
    );
echo $string;

UPDATE2 - 使用带有 e 修饰符的 preg_replace:

$string = "This is a test";
$string = preg_replace(
        '/^(\w+)/e',
        'yourUCLastAlgorithm("$1")',
        $string
    );
echo $string;

【讨论】:

  • 你不觉得用 lamda 函数的正则表达式在这里有点矫枉过正吗,当你可以用泛型函数做到这一点时?
  • 还有一个想法:使用 preg_replace 和 e 修饰符。
  • 通常我总是尝试使用正则表达式而不是自定义拆分解决方案。
【解决方案3】:

试试这个:

$string = preg_replace('/^([ ]+)?([^ ]*)([a-z])?(.*)?$/i', "$1.$2.strtoupper($3).$4", $string);

【讨论】:

  • 如果不需要,为什么要使用正则表达式?太贵了
  • 因为这是第一个想法^^'
  • This is a test => .This.strtoupper(). is a test 发帖前请确认。
猜你喜欢
  • 1970-01-01
  • 2018-06-22
  • 2010-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
相关资源
最近更新 更多