开发者

Another Capitalization question

here is what I am trying to do. I have titles to pages. I'm trying to capitalize the last letter of the first word in each string

Examples:

hellO

hellO how are you

I can get it to work with one word but I cant figure out how to do it if there is more than one word. Any help woul开发者_C百科d be great!!

Thanks so much!


try this

<?php

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

    print $title;

If you want to read more on any function see explode, strrev, list, ucfirst


Since you know the way how this works with 1 word, you only need to get the first word and then put your algorithm.

  1. Try preg_replace_callback with "/^(\w+)/"
  2. Replace the last char within the callback method.

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

UPDATE - working code:

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

UPDATE2 - using preg_replace with e modifier:

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


Try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜