如何在php中创建一个函数replaceMe():
$str = 'This is a very long string';
成:
'This is a very long STRING?'
有人可以帮助我吗?
答案 0 :(得分:4)
你显然想要做一个正则表达式替换,锚定在行的末尾。使用preg_replace
:
$str = 'This is a very long string';
# This is a very long LINE
echo preg_replace("/string$/", "LINE", $str);
对于一般情况,您可以提供回调而不是替换字符串,只需使用preg_replace_callback
将匹配的子字符串大写:
$str = 'This is a very long blah';
function word_to_upper($match) {
return strtoupper($match[1]);
}
# This is a very long BLAH
echo preg_replace_callback("/(\w+)$/", "word_to_upper", $str);
如果您使用的是PHP 5.4或更高版本,则可以将回调作为匿名函数提供:
echo preg_replace_callback("/(\w+)$/", function ($match) {
return strtoupper($match[1])
}, $str);
答案 1 :(得分:3)
这有效:
$str = 'This is a very long string';
echo $str."<br/>";
function replaceMe($str = "")
{
$words = explode(" ",$str);
$totalwords = count($words)-1;
$lastword = $words[$totalwords];
$words[$totalwords] = strtoupper($lastword);
$str = implode(" ",$words);
return $str;
}
echo replaceMe($str);
?>
输出:
这是一个很长的字符串
这是一个非常长的STRING
答案 2 :(得分:-1)
$str = 'This is a very long string.';
function lastWordUpper($str){
$temp = strrev($str);
$last = explode(" ", $temp, 2);
return strrev(strtoupper($last[0]). ' ' .$last[1]) ;
}
echo lastWordUpper($str);