加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 16:43:17 所属栏目:PHP教程 来源:网络整理
导读:我想在一定数量或单词后面插入另一个文本字符串.例如: $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 wo
我想在一定数量或单词后面插入另一个文本字符串.例如:

$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文本非常长.

提前致谢.

解决方法

试试这个:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读