str_replace in post_content with increment value u

2019-09-20 15:18发布

问题:

$selected_publications = $post->post_content;

$ii = 0;

$getLi = array("<li>","</li>");

$replaceLi   = array("<li><div>$ii</div><p>","</p></li>"); 

$selectedPublications = str_replace($getLi, $replaceLi, $selected_publications);

echo $selectedPublications;

There has uncountable li tag for this reason this loop for($ii=0; $ii <= 10; $ii++) is limited for 10 li tag, I think that If li tag 5 , it will loop 5 times. if 15 li tag , it will 15 times loop. I think for($ii=0; $ii <= 10; $ii++) is not actual solution for my problem.

回答1:

This should fix your problem

$selected_publications = "<li>some data</li>";
for($ii=0; $ii <= 10; $ii++)
{
$getLi = array("<li>","</li>");
$replaceLi   = array("<li><div>$ii</div><p>","</p></li>"); 
$selectedPublications = str_replace($getLi, $replaceLi, $selected_publications);

echo $selectedPublications;
}

another way you can do this to show the numbers of each itemization is like this

echo '<ul>';
$selected_publications = "<li style='list-style-type: none;'>some data</li>";
for($ii=0; $ii <= 10; $ii++)
{
$i=$ii;
$getLi = array("<li>","</li>");
$replaceLi   = array("<li><div>$ii</div><p>","</p></li>"); 
$selectedPublications = str_replace($getLi, $replaceLi, $selected_publications);

echo $i.' '.$selectedPublications;
}
echo '</ul>'; 

ignore the html and styling it was added to look better in my eyes.

$ii <= 10 is a conditional statement, it can be changed to something like $ii > 0 which in turn will loop as many times as it needs to.



回答2:

$selected_publications = $post->post_content;
$pieces = explode("</li>", $selected_publications); 
$selectedPublication[]='';  
for($i=0;$i<count($pieces);$i++){       
$getLi = array("<li>","</li>");
$ii = $i+1;
$replaceLi   = array("<li><div>$ii</div><p>","</p></li>");              
$selectedPublication[$i] = str_replace($getLi, $replaceLi, $pieces[$i]);
    echo $selectedPublication[$i];      
}

I have solved my above problem.



标签: php wordpress