Php 向函数添加异常

Php 向函数添加异常,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 .= (

我有一个函数,用于获取字符串并将其转换为所需的形式,即句子大小写

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 = clean_spaces($new_string);
$new_string = m_r_e_s($new_string);
return trim($new_string);
}

现在我想修改“I”的这个函数,因为每当我们有“I in out”语句时,它都是大写的。我如何才能为诸如“I”、“I”等特殊单词添加例外情况。

您可以在小写字符串上使用str_replace
$new_string=str_replace('I',I',$new string)
。对于简单的替换,字符串操作比preg便宜。但是,每个代词都需要一个例外。

这将使
aaaaaaaa i aaaaaa
变成
aaaaaa iaaaa
如果是“i”,它是否正确
preg_replace('/\bi\'/','i',$new_string)@Dani,不会的
\b
是一个锚。@Rahul Singh,表达式将替换
i
,`i
i
i'
,i
,等等。您不需要以任何方式将其改编为
i`后跟
<代码>\b
表示“单词边界”。任何不属于单词的
i
都将被替换。再想一想,preg单词边界是一种更优雅的查找单词的方法,而不是使用空格+对于
i
后面的每个可能的标点符号,您还需要一个不同的
str_replace()
调用。。。
preg_replace('/\bi\b/', 'I', $new_string);