2012-02-10 48 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

相关问题