Jump to content

[SOLVED] Function that UNformats text


fri3ndly

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.