2017-06-18 5 views
0

おはよう! 私は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

$ new_contentは定義されていません!私はそれをテストしました。 content.if($ count == 1)の前または後にstring_to_insertを置きます.2つ以上のコンテンツがある場合は – 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; 
} 
関連する問題