2017-06-18 67 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; 
}