带函数的字符串大小写转换

时间:2011-11-16 07:12:41

标签: php

我在句子中使用了一个函数进行格式化。我的PHP脚本函数是

function sentence_case( $string ) {
    $sentences  = preg_split(
        '/([.?!]+)/', 
        $string, 
        -1, 
        PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
    );

    $new_string = '';
    foreach ( $sentences as $key => $sentence ) {
        $new_string .= ( $key & 1 ) == 0 
            ? ucfirst( strtolower( trim( $sentence ) ) ) 
            : $sentence . ' ';
    }
    $new_string = preg_replace( "/\bi\b/", "I", $new_string );
    //$new_string = preg_replace("/\bi\'\b/", "I'", $new_string);
    $new_string = clean_spaces( $new_string );
    $new_string = m_r_e_s( $new_string );
    return trim( $new_string );
}

虽然它顺利并且在句子中转换整个字符串。但我希望它会在单引号中跳过字符。就像我的字符串HeLLO world! HOw aRE You.正在转换为Hello world! How are you?一样,但我想跳过单引号中的内容。就像我希望跳过单引号中的单词一样。 'HELLO' World并将单引号中的单词转换为大写,否则字符串应保留在句子中。

2 个答案:

答案 0 :(得分:3)

您可以在单引号中为大写单词添加另一个简单的正则表达式回调。 (这是我理解你想做的事。)

$new_string = preg_replace("/'(\w+)'/e", 'strtoupper("\'$1\'")', $new_string);

如果您希望每个引号使用多个单词,请使用[\w\s]+代替\w+。但是,这会使文本中isn't之类的短语更容易失败。

答案 1 :(得分:2)

以下是此任务的紧凑且可行的解决方案:

    $s = preg_replace_callback("~([\.!]\s*\w)|'.+?'~", function($args) {
      return strtoupper($args[sizeof($args) - 1]);
    }, ucfirst(strtolower($s)));

以下输入:

    $s = "HeLLO world! HOw aRE You 'HELLo' iS QuOTed and 'AnothEr' is quoted too";

它会产生:

    Hello world! How are you 'HELLO' is quoted and 'ANOTHER' is quoted too

P.S。 如果您使用的是PHP< 5.3你可以将回调移动到单独的函数中。