2012-02-10 65 views
4

我想在某個數字或單詞之後插入另一個文本字符串。例如:如何在一定數量的單詞之後插入文本

$text_to_add = "#Some Text to Add#"; 
$text_original = "This is the complete text in which I want to insert the other text"; 
$number_words = 7; // Variable that will define after how many words I must put $text_to_add 

我想,當我打印到得到以下結果$ text_original:

這是完整的文本中#Some文本添加#我要插入的其他文本

我可以使用這個函數http://php.net/manual/en/function.str-word-count.php來獲取一個單詞數組,通過它建立一個插入$ text_to_add的新字符串,但我想知道是否有更好的方法來完成這個,因爲我的一些$ text_original文本是很長。

在此先感謝。

回答

3

試試這個:

$arr = explode(" ",$text,$number_words+1); 
$last = array_pop($arr); 
return implode(" ",$arr)." ".$text_to_add." ".$last; 
+1

謝謝,完美的作品。 – leticia 2012-02-10 21:56:36

相關問題