2013-04-22 120 views
0

我想寫將通過以下方式修改字符串的函數:在單詞的末尾放置一個字一個字符串

如果字符串「的」在開始的時候,我想剪下來,並將','添加到字符串的末尾。

我的代碼不工作 - 我想知道如何解決它,以便它的工作。

<?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; 
    } 
?> 
+2

你字符串不以''開始。 – Paulpro 2013-04-22 00:03:46

+0

只是一個例子。我用很多不同的字符串對它進行了測試。 – JimRomeFan 2013-04-22 00:12:45

回答

4

使用正則表達式可能是這個任務更好:因爲你的strpos()結果需要到strict comparison

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

而且,你的代碼是不工作:

if ($pos === 0 && strlen($string) > 4) { 
// ... 
+0

謝謝,定時器允許我接受答案。 – JimRomeFan 2013-04-22 00:07:11

相關問題