简体   繁体   English

在PHP中X个字符(外部HTML)之后,从数组插入String

[英]Insert String from Array after X amount of characters (Outside HTML) in PHP

I've looked and can't find a solution to this feature we would like to write. 我已经看过,但找不到我们要编写的此功能的解决方案。 I'm fairly new to PHP so any help, advice and code examples are always greatly appreciated. 我对PHP还是很陌生,因此总是非常感谢任何帮助,建议和代码示例。

Let me explain what we want to do... 让我解释一下我们想做什么...

We have a block of HTML inside a string - the content could be up to 2000 words with styling such as <p> , <ul> , <h2> included in this HTML content string. 我们在字符串内有一个HTML块-该HTML内容字符串中包含的内容最多可以包含2000个单词,且带有样式,例如<p><ul><h2>

We also have an array of images related to this content inside a separate string. 在单独的字符串中,我们还具有与此内容相关的图像数组。

We need to add the images from the array string into the HTML content at equal spaces without breaking the HTML code. 我们需要将数组字符串中的图像以相等的间隔添加到HTML内容中,而不会破坏HTML代码。 So a simple character count won't work as it could break the HTML tags. 因此,简单的字符计数将无法工作,因为它可能会破坏HTML标签。

We need to equally space the images. 我们需要等距排列图像。 So, for example; 因此,例如; if we had 2000 words inside the HTML content string and 10 images in the array, we need to place an image every 200 words. 如果HTML内容字符串中有2000个单词,数组中有10个图像,则需要每200个单词放置一个图像。

Any help or coding samples provided in order to achieve this is greatly appreciated - thank you for your help in advance. 为实现此目的而提供的任何帮助或编码示例都将不胜感激-提前感谢您的帮助。

You can use 您可以使用

$numword =  str_word_count($str, 0); 

for getting the number of row 获取行数

or 要么

$array = str_word_count($str,1);

for getting in $array an array with all the word (one for index) and then iterating on this array for rebuild text you need adding every number of time (word) the code for your image 为了在$ array中获得一个包含所有单词的数组(一个用于索引),然后在该数组上迭代以重建文本,您需要为图像添加代码的每个时间(单词)

This Sample is form php Manual 此样本是php手册的表格

 <?php $str = "Hello fri3nd, you're looking good today!"; print_r(str_word_count($str, 1)); print_r(str_word_count($str, 2)); print_r(str_word_count($str, 1, 'àáãç3')); echo str_word_count($str); ?> 

this is related result 这是相关的结果

 Array ( [0] => Hello [1] => fri [2] => nd [3] => you're [4] => looking [5] => good [6] => today ) Array ( [0] => Hello [6] => fri [10] => nd [14] => you're [29] => looking [46] => good [51] => today ) Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today ) 7 

You can find it in this doc 您可以在此文档中找到它

for the insert you can try this way 对于插入,您可以尝试这种方式

$num = 200;  // number of word after which  inert the image
$text = $array[0]; // initialize the text with the first word in array

for ($cnt =1; $cnt< count( $array); $cnt++){
   $text .= $array[$cnt];  // adding the word to the text 
   if (($cnt % $num) == 0) {   // if  array index multiple fo 200 insert the image
    $text .= "<img src='your_img_path' >";
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM