php - Using preg_replace to display paragraphs, can a photo be added to each paragraph?


I am working on building a news section for one of my sites. I am storing the information for each news article in a database tablenews, the main text of the article is in columncopy whose type is set tolongtext.

I use the following line of code to display the news article as paragraphs:

<p ><?php echo preg_replace('/[\r\n]+/', '</p><p >', $news['copy']); ?></p>

and it works absolutely perfect.

The reason for this post is because I would like to be able to display more than one photo for each news article. I am setting a lead image in the database, but if there were, say, 4 other photos in one story and 6 in another (in addition to the lead image) is there any way for me to display, say, 1 or more photo(s) per paragraph?

I'll be happy to elaborate in case this is too confusing.

Many thanks!




<?php echo insert_par_and_photos($news['copy'], $news['photos']); ?>

function insert_par_and_photos($copy, $photos) {
  $pars = preg_split('/[\r\n]+/', $copy);
  $result = '';
  foreach ($pars as $i => $par) {
    $result .= '<p class="news_copy">';
    $result .= $par;
    if ($i < count($photos)) {
      $result .= '<img src="'+$photos[$i]+'"/>';
    $result .= '</p>';        
  return $result;

People are also looking for solutions to the problem: PHP - get defined constants for a given namespace


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.