Php 将句子的第一个单词替换为“如果”;";

Php 将句子的第一个单词替换为“如果”;";,php,Php,如果一个句子的第一个单词是“the”,我想在它的前面用逗号替换它,例如,如果我有电影标题:饥饿游戏,我想它变成:饥饿游戏 这可能吗?如果可能,我如何让它工作?使用: echo custom_func('The Hunger Games'); function custom_func($s) { $s = trim(preg_replace('~\s+~', ' ', $s)); $a = explode(' ', $s); if (strtolower($a[0]) !

如果一个句子的第一个单词是“the”,我想在它的前面用逗号替换它,例如,如果我有电影标题:饥饿游戏,我想它变成:饥饿游戏

这可能吗?如果可能,我如何让它工作?

使用:

echo custom_func('The Hunger Games');
function custom_func($s) {
    $s = trim(preg_replace('~\s+~', ' ', $s));
    $a = explode(' ', $s);
    if (strtolower($a[0]) != 'the' || count($a) < 2) return $s;
    $the = array_shift($a);
    return implode(' ', $a) . ', ' . $the;
}
功能:

echo custom_func('The Hunger Games');
function custom_func($s) {
    $s = trim(preg_replace('~\s+~', ' ', $s));
    $a = explode(' ', $s);
    if (strtolower($a[0]) != 'the' || count($a) < 2) return $s;
    $the = array_shift($a);
    return implode(' ', $a) . ', ' . $the;
}
函数自定义函数($s){
$s=修剪(预替换(“~\s+~”,“$s”);
$a=爆炸(“”,$s);
如果(strtolower($a[0])!=“the”| | count($a)<2)返回$s;
$the=数组的移位($a);
返回内爆(“”,$a)。“,”。$the;
}

请尝试以下操作:

<?
$str = 'The Hunger Games';
if (strtolower(substr($str,0,3)) == "the"){
    $str = trim(substr($str,3)).', The';
}
echo $str;
?>


查看
explode()
,并确定是否可能。do\u magic函数名为+1-do_magic函数名为1。您已经删除了+1部分,但-1仍然在这里。尝试使用一个有意义的函数名:)@STTLCU:我认为这取决于用户是否重命名函数名,答案只是为了演示。我可以很容易地写下这个例子而不使用函数…如果用户输入“结束”怎么办?他将得到输出“END,The”…@Glavićjust replace
,“
,”。substr($str,0,3)
@WimMostmans:我知道如何编写工作代码,但答案应该对未来的新手有效。