2017-06-18 68 views
0

美好的一天EB! 我是一個PHP新手,並堅持一些簡單的任務。使用substr_replace發佈內容操作

我想插入一個字符串後第5完全停留在發佈內容。但是,我仍然堅持寫第一步替換。之後,我會將計數添加到$ pos。 我也嘗試過substr_replace()。

這是我的代碼在我的主題的function.php文件中。

function replace_content($content) 
{ 
    $oldstr = $content; 
    $str_to_insert = "tst"; 
    $pos = 30; 
    $new_content = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos); 


    return $new_content; 
} 
add_filter('the_content','replace_content'); 

它沒有返回預期的結果。 感謝您的建議和幫助。

回答

0

我不確定,如果有任何內建方法存在。但是,有解決方法您的問題

你可以使用explode和循環在一起

$array = array(".",$content); //split by fullstop and store it in array 
$new_content = "" 
$str_to_insert = "tst"; 
$count=1 

foreach($array as $value) { // loop through the array now 
    if($count==5) 
    { 
    $new_content = $new_content.$value.$str_to_insert."."; // insert string on fifth occurrence 
    } 
    else 
    { 
    $new_content = $new_content.$value."."; // otherwise just append string as it was 
    } 
$count++; 
} 
+0

我想你錯過了st。 $ new_content沒有定義!?我測試了它。它在content.if($ count == 1)之前或之後放置string_to_insert,或者如果($ count == 2)同時內容大於2則放置string_to_insert。 – user2047710

+0

我沒有找到你。我只是提供了一個工作 – Ravi

+0

是的,10倍。這是個好主意,但不是真的有效。爲什麼你有$ new_content =「」空白?不應該是裏面的數組? – user2047710

0

那麼你可以只使用爆炸功能的第五發生後添加字符串「」。例如,您可以使用以下功能:

function replace_content($content) 
{ 
    $str_to_insert = "tst"; 
    $pos = 5; 

    $data = explode(".", $content); 
    $data[5] = $str_to_insert . " " . $data[5]; 
    $new_content = implode(".", $data); 

    return $new_content; 
}