0

我正在尝试编写一个函数,该函数将通过以下方式修改字符串:

如果字符串的开头有'The',我想把它剪掉并在字符串的末尾添加', The'。

我的代码不起作用 - 我想知道如何修复它以使其正常工作。

<?php

    $string = 'Wonderful World of Disney';
    $search_term = 'The ';
    $str_replace = ', The';
    $pos = strpos($string, $search_term);
    if ($pos==0 && strlen($string) > 4) {
        $clean_str = substr($string, 4, strlen($string));
        $clean_str = $clean_str . $str_replace;
        echo $clean_str;
    }
?>
4

1 回答 1

4

对于此任务,使用正则表达式可能会更好:

$clean_str = preg_replace('/^The (.*)$/', '$1, The', $string);

此外,您的代码不起作用,因为您需要对以下结果进行严格比较strpos()

if ($pos === 0 && strlen($string) > 4) {
// ...
于 2013-04-22T00:03:36.870 回答