putting \r (return) after 74th character

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ansa
Forum Commoner
Posts: 31
Joined: Tue Aug 29, 2006 1:58 am
Location: Hamburg, Germany

putting \r (return) after 74th character

Post 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!
amir
Forum Contributor
Posts: 287
Joined: Sat Oct 07, 2006 4:28 pm

Post 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;
?>
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post 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);
}
Last edited by s.dot on Thu Oct 19, 2006 5:08 am, edited 1 time in total.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

or wordwrap :oops: :oops: :oops:
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
ansa
Forum Commoner
Posts: 31
Joined: Tue Aug 29, 2006 1:58 am
Location: Hamburg, Germany

Post by ansa »

wordwrap works good! Sometimes I'm amazed how powerful PHP can be... :)

Thanks guys.
Post Reply