Php 带函数的字符串大小写转换
我使用了一个函数来设置句子大小写的格式。我的PHP脚本函数是Php 带函数的字符串大小写转换,php,Php,我使用了一个函数来设置句子大小写的格式。我的PHP脚本函数是 function sentence_case( $string ) { $sentences = preg_split( '/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE ); $new_string = ''; foreach (
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并将单引号中的单词转换为大写,否则字符串应保持句子大小写。您可以向单引号中的大写单词添加另一个简单的正则表达式回调。(这就是我理解你想要做的。)
如果您想让每个报价单包含多个单词,请使用
[\w\s]+
代替\w+
。然而,这会使它更容易失败,因为像这样的短语不在文本中。您可以在单引号中向大写单词添加另一个简单的regex回调。(这就是我理解你想要做的。)
如果您想让每个报价单包含多个单词,请使用[\w\s]+
代替\w+
。但是,这会使文本中没有这样的短语更容易失败。以下是此任务的简洁有效的解决方案:
$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
附言。
如果您使用的是PHP<5.3,则可以将回调移到单独的函数中。以下是此任务的简洁有效的解决方案:
$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
附言。
如果您使用的是PHP<5.3,您可以将回调移到单独的函数中。请注意:在这里,专有名词会给您带来各种麻烦。我不认为他是说您的英语不好,但是专有名词应该大写。只是提醒一下:你在这里会遇到各种各样的专有名词的麻烦。我想他不是说你的英语不好,而是说专有名词应该大写。这是在给字符串加上斜线。就像\\\\'HELLO\\\\'世界一样。大家好
这是在输出中添加斜杠。真奇怪。添加stripslashes(…)
然后围绕strtoupper(…)
向字符串添加斜杠。就像\\\\'HELLO\\\\'世界一样。大家好
这是在输出中添加斜杠。真奇怪。添加stripslashes(…)
然后在strtoupper(…)