本文实例讲述了php字符串word末字符实现大小写互换的方法。分享给大家供大家参考。具体实现方法如下:
一、要求:
给出一个字符串如 “a journey of, a thousand 'miles' must can't \begin\ with a single step.” ,通过 php 程序处理变成 “a journey of, a thousand 'miles' must can't begin with a single step.”
这里需要注意:
1、每个单词最后的字符如果是大写就变成小写,如果是小写就变成大写。
2、需要考虑类似 can't 这种形式的转换。
3、标点符号(只考虑 , ' . ;)不用变化。
二、参考算法如下:
代码如下:
function convertlastchar($str) {
$markarr = array(, , ' , \ , . , ; );
$ret = ;
for ($i = 0, $j = strlen($str); $i if ($i $afterstr = $str{$i + 1} . $str{$i + 2};
} else if ($i $afterstr = $str{$i + 1} . ;
}
if (in_array($afterstr, $markarr)
|| $i == $j - 1
|| $str{$i + 1} == ) {
$ret .= strtoupper($str{$i}) === $str{$i}
? strtolower($str{$i})
: strtoupper($str{$i});
} else {
$ret .= $str{$i};
}
}
return $ret;
}
?>
测试代码如下:
代码如下:
//test
$str1 = a journey of, a thousand 'miles' must can't \begin\ with a single step.;
$str2 = a journey of, a thousand 'miles' must can't \begin\ with a single step. ;
$str3 = a journey of, a thousand 'miles' must can't \begin\ with a single step. a ;
$str4 = a journey of, a thousand 'miles' must can't \begin\ with a single step. a b;
$str5 = a journey of, a thousand 'miles' must can't \begin\ with a single step. a b';
$str6 = a journey of, a thousand 'miles' must can't \begin\ with a single step. a b\;
echo source:
. $str1 .
result:
. convertlastchar($str1) .
;
echo source:
. $str2 .
result:
. convertlastchar($str2) .
;
echo source:
. $str3 .
result:
. convertlastchar($str3) .
;
echo source:
. $str4 .
result:
. convertlastchar($str4) .
;
echo source:
. $str5 .
result:
. convertlastchar($str5) .
;
echo source:
. $str6 .
result:
. convertlastchar($str6) .
;
?>
运行结果如下:
代码如下:
source:
a journey of, a thousand 'miles' must can't begin with a single step.
result:
a journey of, a thousand 'miles' must can't begin with a single step.
source:
a journey of, a thousand 'miles' must can't begin with a single step.
result:
a journey of, a thousand 'miles' must can't begin with a single step.
source:
a journey of, a thousand 'miles' must can't begin with a single step. a
result:
a journey of, a thousand 'miles' must can't begin with a single step. a
source:
a journey of, a thousand 'miles' must can't begin with a single step. a b
result:
a journey of, a thousand 'miles' must can't begin with a single step. a b
source:
a journey of, a thousand 'miles' must can't begin with a single step. a b'
result:
a journey of, a thousand 'miles' must can't begin with a single step. a b'
source:
a journey of, a thousand 'miles' must can't begin with a single step. a b
result:
a journey of, a thousand 'miles' must can't begin with a single step. a b
希望本文所述对大家的php程序设计有所帮助。