如何在一定数量的单词后插入文本

发布于 2025-01-05 04:54:01 字数 636 浏览 1 评论 0原文

我想在特定数字或单词之后插入一个文本字符串到另一个文本字符串中。例如:

$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 Text to Add#我想插入其他文本

我可以使用这个函数http://php.net/manual/en/function.str-word-count .php 获取单词数组,遍历它构建一个插入 $text_to_add 的新字符串,但我想知道是否有更好的方法来完成此操作,因为我的一些 $text_original 文本非常长。

提前致谢。

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

$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 I print $text_original:

This is the complete text in which #Some Text to Add# I want to insert the other text

I can use this function http://php.net/manual/en/function.str-word-count.php to get an array of words, go through it building a new string with the $text_to_add inserted, but I wondering if there is a better way to accomplish this, since some of my $text_original texts are very long.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

裸钻 2025-01-12 04:54:01

试试这个:

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

Try this:

$arr = explode(" ",$text,$number_words+1);
$last = array_pop($arr);
return implode(" ",$arr)." ".$text_to_add." ".$last;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文