Page 1 of 1

putting \r (return) after 74th character

Posted: Thu Oct 19, 2006 3:14 am
by ansa
Hi,

I have a plain text (consists of paragraphs) for a newsletter, and it has to be 74-character long (included spaces) for each line. That means I have to put '\r' after the 74th character. To make things a little bit more challenging :) , if a line has already '\r' in it, then we should not put another '\r'.

I was thinking that the logic would be:

first, check if within every 75 characters a '\r' already exists. If yes, then don't do anything. If no, insert '\r'. After inserting '\r', the next character is set back to 1st character (place 1), to count the next 75 characters.

I just don't know how to implement that with PHP. Or maybe there's a better idea.

Appreciate that!

Posted: Thu Oct 19, 2006 4:44 am
by amir

Code: Select all

<?php
$text = "Please check this one if it works for you then its very good. Cheers.";
$newtext = wordwrap($text, 74, "<br />\n");

echo $newtext;
?>

Posted: Thu Oct 19, 2006 5:06 am
by s.dot
This is thoroughly untested.

Code: Select all

function check_length($p)
{
	$strlen = strlen($p);
	$chunk = 74;
	
	$ret = array();
	for($i=0;$i<ceil($strlen/$chunk);$i++)
	{
		if(strpos("\n", substr($p,$i*$chunk,$chunk)) !== false)
		{
			$lines = explode("\n", substr($p,$i*$chunk,$chunk));
			foreach($lines AS $line)
			{
				$ret[] = $line;
			}
		} else
		{
			$ret[] = substr($p,$i*$chunk,$chunk);
		}
	}
	
	return implode("\n",$ret);
}

Posted: Thu Oct 19, 2006 5:08 am
by s.dot
or wordwrap :oops: :oops: :oops:

Posted: Thu Oct 19, 2006 10:09 am
by ansa
wordwrap works good! Sometimes I'm amazed how powerful PHP can be... :)

Thanks guys.