Jump to content

Recommended Posts

Hi all!

 

I recently found and am using the following fuction that will format  entered text into paragraphs:

 

function formatString($string)
{
      $x_string = explode("\r\n\r\n",trim($string)); // explode on double carriage returns
      $x_count = count($x_string);
      $string = '';
      for($i=0; $i<$x_count; $i++){
      	$string .= '<p>'.$x_string[$i].'</p>';
      }
    return str_replace('<p></p>','',$string); // removes empty paragraphs
}

 

Is is possible to make a function that will reverse this (for the sake of editing through a CMS)? If so can someone give me some guidelines?

Link to comment
https://forums.phpfreaks.com/topic/87373-solved-function-that-unformats-text/
Share on other sites

First, you should always store the original string and only use functions like this when writing to the screen. Then, you wouldn't need to reverse it.

 

Next, you can shorten your function by using the implode() function:

<?php
function formatString($string)
{
      $x_string = explode("\r\n\r\n",trim($string)); // explode on double carriage returns
      $string = str_replace('<p></p>','','<p>' . implode('</p><p>',$x_string) . '</p>');
      return $string;
}?>

 

You also may just be able to use the nl2br() function:

<?php
function formatString($string) {
   return(nl2br($string));
}
?>

 

Using the strip_tags() function, does not give you the original string back. Your new string will not have the "\r\n" characters in it.

 

Ken

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.