如何在PHP中使用其他角色?

时间:2011-08-22 21:26:21

标签: php regex string capitalize

我想在PHP中使用CaPiTaLiZe $ string,不要问为什么:D

我做了一些研究并在这里找到了很好的答案,他们真的帮助了我。 但是,在我的情况下,我想开始大写每个奇怪的字符(1,2,3 ......)。

例如,使用我的自定义函数,我得到了这个结果“TeSt eXaMpLe”,并希望得到这个“TeSt ExAmPlE”。 看到第二个例子中的单词“example”以大写“E”开头?

那么,任何人都可以帮助我吗? :)

5 个答案:

答案 0 :(得分:2)

好吧,我只是把它变成一个数组,然后再把它重新组合起来。

<?php

$str = "test example";

$str_implode = str_split($str);

$caps = true;
foreach($str_implode as $key=>$letter){
    if($caps){
        $out = strtoupper($letter);
        if($out <> " ") //not a space character
            $caps = false;
    }
    else{
        $out = strtolower($letter);
        $caps = true;
    }
    $str_implode[$key] = $out;
}

$str = implode('',$str_implode);

echo $str;

?>

演示:http://codepad.org/j8uXM97o

答案 1 :(得分:2)

我会使用正则表达式来执行此操作,因为它简洁易行:

$str = 'I made some research and found good answers here, they really helped me.';
$str = preg_replace_callback('/(\w)(.?)/', 'altcase', $str);
echo $str;

function altcase($m){
    return strtoupper($m[1]).$m[2];
}

输出:“我可能会重新找到他们,并且可能会让他感到沮丧,但是他仍然能够帮助我。”

Example

答案 2 :(得分:1)

这是一个应该有用的衬垫。

preg_replace('/(\w)(.)?/e', "strtoupper('$1').strtolower('$2')", 'test example');

http://codepad.org/9LC3SzjC

答案 3 :(得分:1)

尝试:

function capitalize($string){
    $return= "";
    foreach(explode(" ",$string) as $w){
        foreach(str_split($w) as $k=>$v) {
            if(($k+1)%2!=0 && ctype_alpha($v)){
                $return .= mb_strtoupper($v);
            }else{
                $return .= $v;
            }
        }
        $return .= " ";
    }
    return $return;
}
echo capitalize("I want to CaPiTaLiZe string in php, don't ask why :D");
//I WaNt To CaPiTaLiZe StRiNg In PhP, DoN'T AsK WhY :D

已修改:修复了输出中缺少特殊字符的问题。

答案 4 :(得分:0)

无需使用捕获组即可执行此任务-只需使用ucfirst()

这不是用来处理多字节字符的。

抓住一个单词字符,然后选择下一个字符。从全串匹配开始,仅更改第一个字符的大小写。

代码:(Demo

$strings = [
    "test string",
    "lado lomidze needs a solution",
    "I made some research and found 'good' answers here; they really helped me."
];  // if not already all lowercase, use strtolower()

var_export(preg_replace_callback('/\w.?/', function ($m) { return ucfirst($m[0]); }, $strings));

输出:

array (
  0 => 'TeSt StRiNg',
  1 => 'LaDo LoMiDzE NeEdS A SoLuTiOn',
  2 => 'I MaDe SoMe ReSeArCh AnD FoUnD \'GoOd\' AnSwErS HeRe; ThEy ReAlLy HeLpEd Me.',
)

对于其他研究人员,如果(只是简单地)只想将其他所有字符都转换为大写字母,则可以 在模式中使用/..?/,但在这种情况下使用正则表达式将是过度杀伤力。您可以更有效地使用for()循环和双增量。

代码(Demo

$string = "test string";
for ($i = 0, $len = strlen($string); $i < $len; $i += 2) {
    $string[$i] = strtoupper($string[$i]);
}
echo $string;
// TeSt sTrInG
// ^-^-^-^-^-^-- strtoupper() was called here