How to insert text after word count

I want to insert a text string inside another after a certain number or words. For instance:

$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 

I want to get the following result when printing $ text_original:

This is the full text in which #Some Text to add # I want to insert another text

I can use this function http://php.net/manual/en/function.str-word-count.php to get an array of words, go through this by building a new line with $ text_to_add inserted, but I wonder if there is the best way to do this, as some of my text texts are very long.

Thanks in advance.

+4
source share
1 answer

Try the following:

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

Source: https://habr.com/ru/post/1395845/


All Articles