简体   繁体   中英

Split variable content into multiple paragraphs

Hey there, I have this little php code:

<p class="category_text"><? echo $category_text; ?></p>

I waht to split the $category_text and get something like this:

This is sentence 1 of category_text

This is sentence 2 of category_text

and so on...

$category_text has about 300 words and lets say 6 sentences. How could I split the text in multiple paragraphs (delimited by the stop sings ".")

Thank you very much!

echo  '<p class="category_text">' 
      . implode('</p><p class="category_text">', explode('.',$string))
      .'</p>';

You can just replace the "." by the tag "
":

<p class="category_text"><? echo str_replace('.', '.<br />', $category_text); ?></p>

It's not a perfect solution! But if you text is simple enough this little trick should work.

For example if you have a line with 3 dots:

$category_text = "Ok...";

It will show up like that:

OK.
.
.

Also if your sentences finish by "?" or "!" you can also use that:

<p class="category_text"><? echo str_replace(array('.', '!', '?'), array('.<br />', '!<br />', '?<br />'), $category_text); ?></p>

PS: My solution will create one paragraph "

" but with multiple line break

Try creating an array, and then output the lines one by one. A sentence ending in ... would still be recognized as still ends in ". ".

$sentences = explode('. ', $category_text)

foreach($sentences as $val)
{
    echo $val . ".<br /><br />";
}

You want to split a text into sentences, which is not trivial - using explode(".", $string) does often not give good results.

Search Stackoverflow for "php split sentence", or directly try the solution to PHP: Parse document / text into sentences :

http://www.zubrag.com/scripts/text-splitter.php

Once you have an array with sentences, use

echo '<p>' . implode('</p><p>', $sentences) . '</p>';

to echo them out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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