2

我如何在 php 中创建一个函数 replaceMe(),它会变成:

$str = 'This is a very long string';

进入:

'This is a very long STRING?'

有人能帮我吗?

4

3 回答 3

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);
于 2012-08-14T19:43:45.173 回答
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);
?>

输出:

这是一个很长的字符串
这是一个很长的字符串

于 2012-08-14T19:46:35.203 回答
-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);
于 2012-08-14T20:45:30.700 回答