473,593 Members | 2,885 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

php word wrap function needed - one that works

I have been looking for a php word wrap function. I know there's an
official PHP function but I've tried that and many of the functions
contributed on that php.net page and none do what I want...and some act
weird as well.

I want, If I say break at 150 chars then the function will break at the
nearest space to 150 ie. it will actually break at the word boundry. And
if theres a url it will not break inside a URL, it will leave URLS alone.

Please state/link me *specifically* what function if you know of one,
Thanks for the help,
Lee G.
Jul 17 '05 #1
6 6145
function iTrunc($string, $length) {
if (strlen($string )<=$length) {
return $string;
}

$pos = strrpos($string ,".");
if ($pos>=$length-4) {
$string = substr($string, 0,$length-4);
$pos = strrpos($string ,".");
}
if ($pos>=$length* 0.4) {
return substr($string, 0,$pos+1)." ...";
}

$pos = strrpos($string ," ");
if ($pos>=$length-4) {
$string = substr($string, 0,$length-4);
$pos = strrpos($string ," ");
}
if ($pos>=$length* 0.4) {
return substr($string, 0,$pos)." ...";
}

return substr($string, 0,$length-4)." ...";

}
from an unknown author..
but with slight modification you should be able to get what you want..
this just takes the string, finds the nearest period, word end, or
space at the spec. length and returns the string. This could be
helpful, i'm not sure if it solves any problems.

Jul 17 '05 #2
jblanch wrote:
function iTrunc($string, $length) {
if (strlen($string )<=$length) {
return $string;
}

$pos = strrpos($string ,".");
if ($pos>=$length-4) {
$string = substr($string, 0,$length-4);
$pos = strrpos($string ,".");
}
if ($pos>=$length* 0.4) {
return substr($string, 0,$pos+1)." ...";
}

$pos = strrpos($string ," ");
if ($pos>=$length-4) {
$string = substr($string, 0,$length-4);
$pos = strrpos($string ," ");
}
if ($pos>=$length* 0.4) {
return substr($string, 0,$pos)." ...";
}

return substr($string, 0,$length-4)." ...";

}
from an unknown author..
but with slight modification you should be able to get what you want..
this just takes the string, finds the nearest period, word end, or
space at the spec. length and returns the string. This could be
helpful, i'm not sure if it solves any problems.
I don't know if I can modfiy this to ignore links...

Jul 17 '05 #3
leegold2 wrote:
I don't know if I can modfiy this to ignore links...


One approach would be to let wordwrap do its stuff and replace the unwanted
breaks, example:

function mywordwrap ($str, $length) {
$str = wordwrap($str, $length);
return nl2br(
preg_replace(
"/<([^>]*)[\r\n]([^>]*)>/s",
"<$1 $2>",
$str
)
);
}
JW

Jul 17 '05 #4
Hello,

on 01/02/2005 03:58 AM leegold2 said the following:
I have been looking for a php word wrap function. I know there's an
official PHP function but I've tried that and many of the functions
contributed on that php.net page and none do what I want...and some act
weird as well.

I want, If I say break at 150 chars then the function will break at the
nearest space to 150 ie. it will actually break at the word boundry. And
if theres a url it will not break inside a URL, it will leave URLS alone.

Please state/link me *specifically* what function if you know of one,


Yes, I also had to ditch PHP wordwrap function because of its bugs. I
use my own implementation in a class that I use composing and sending
e-mail message. It is used to break long lines and optionally mark them
with some quoting marks if necessary.

It is just meant to break plain text but you are free to modify it to
skip HTML tags:

http://www.phpclasses.org/mimemessage
--

Regards,
Manuel Lemos

PHP Classes - Free ready to use OOP components written in PHP
http://www.phpclasses.org/

PHP Reviews - Reviews of PHP books and other products
http://www.phpclasses.org/reviews/

Metastorage - Data object relational mapping layer generator
http://www.meta-language.net/metastorage.html
Jul 17 '05 #5
leegold2 wrote:
I don't know if I can modfiy this to ignore links...


One approach would be to let wordwrap do its stuff and replace the unwanted
breaks, example:

function mywordwrap ($str, $length) {
$str = wordwrap($str, $length);
return nl2br(
preg_replace(
"/<([^>]*)[\r\n]([^>]*)>/s",
"<$1 $2>",
$str
)
);
}
JW

Jul 17 '05 #6
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

leegold2 wrote:

| I have been looking for a php word wrap function. I know there's an
| official PHP function but I've tried that and many of the functions
| contributed on that php.net page and none do what I want...and some act
| weird as well.
|
| I want, If I say break at 150 chars then the function will break at the
| nearest space to 150 ie. it will actually break at the word boundry. And
| if theres a url it will not break inside a URL, it will leave URLS alone.
|
| Please state/link me *specifically* what function if you know of one,
| Thanks for the help,
| Lee G.

Here is one that I had thrown together a while back:

function word_wrap($char s,$str){
~ $cpy=strip_tags ($str);
~ $chk=array_reve rse(preg_split( '`\s`',$cpy));
~ $chk2=array_rev erse(preg_split ('`\s`',$str));
~ $len=0;
~ $retVal='';

~ // we want to work backwards on this
~ for($i=count($c hk)-1;$i>=0;$i--){
~ // $len is the current segment length in the stripped string
~ if($len>0 && ($len + strlen($chk[$i])) > $chars){
~ // add a line break
~ $retVal.='<br />'."\n";
~ $len=0;
~ }else if($len>0){
~ // space between words needs to be counted
~ $len++;
~ }

~ // add the necessary pieces to the string
~ $pop1=array_pop ($chk); // get next piece from each version
~ $pop2=array_pop ($chk2);
~ $retVal.=$pop2. ' ';
~ $len+=strlen($p op1);
~ $pattern='`'.pr eg_quote($pop1) .'`';
~ while(!preg_mat ch($pattern,str ip_tags($pop2)) ){
~ // if pop1 and pop2 are not referencing the same element
~ $pop2=array_pop ($chk2);
~ $retVal.=$pop2. ' ';
~ if($pop2==NULL) break;
~ }
~ }
~ return $retVal;
}

It wraps plain text or HTML as it displays (doesn't count the HTML tags
when processing). The string is split on whitespace, if there is a piece
that is longer than the wrap, it outputs just that as it was input.

HTH

- --
Justin Koivisto - ju****@koivi.co m
http://www.koivi.com
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFB2tvhm2S xQ7JEbpoRAoeZAJ 9XilXn/AgPBSpdAQe6ihCv pAQKqQCdFVkt
BkTpkYMcJYqJxA8 R552govQ=
=IcB0
-----END PGP SIGNATURE-----
Jul 17 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
23293
by: Jeff B. | last post by:
Has anyone come across a decent algorithm for implementing word wrap features in .net printing? I have a small component that uses basic printing techniques (i.e. e.Graphics.DrawString in a PrintPage event of a PrintDocument object) to send some formatted text to the printer. However, if the lines are too long they run off the page rather than wrapping around. I'm sure I can spend the time and come up with a word wrapping algorithm but...
8
4205
by: John Salerno | last post by:
I figured my first step is to install the win32 extension, which I did, but I can't seem to find any documentation for it. A couple of the links on Mark Hammond's site don't seem to work. Anyway, all I need to do is search in the Word document for certain strings and either delete them or replace them. Easy enough, if only I knew which function, etc. to use. Hope someone can push me in the right direction.
10
72673
by: Lorenzo Thurman | last post by:
I have a table cell that I want to wrap text inside of. I've tried both hard and soft wrap, but Firefox refuses to obey. IE 6&7 handle the wrap just fine. Does anyone know how I can fix this?
5
6730
by: momo | last post by:
say i have the following table: <table width="500"> <tr> <td width="250">this is the text im concerned with</td> <td></td> </tr> </table> i need the width of the columns to STAY at 250 and wrap text that is longer
8
6935
by: gazza67 | last post by:
Hi, I want to do something that I thought would be simple but i cant seem to work it out, perhaps someone out there could help me. I want to browse for a file (it will be a word document), save the file name to a string and then at some later stage open that file with word. The operating system will be windows 2000 (dont know if that makes a difference or not).
4
12427
by: etuncer | last post by:
Hello All, I have Access 2003, and am trying to build a database for my small company. I want to be able to create a word document based on the data entered through a form. the real question is this: can Access create the document and place it as an OLE object to the relevant table? Any help is greatly appreciated. Ricky
6
4618
by: Eric Layman | last post by:
Hi, I have fields from textareas. With a click of a button, php is able to grab these fields and by using header(), convert the output to Ms Word doc. But the outcome of the word doc doesn't wrap the text in textarea. the result is one very veyr long string of text which stretch MS word all
3
7064
by: christianlott1 | last post by:
I needed this for address labels that wouldn't wrap. Couldn't find the function so I made one. Splits at space. Function cvtWordWrap(Apl As String, Leng As Long) As String Dim i As Long If Len(Apl) Leng Then i = 0 Top: If i = Leng Then cvtWordWrap = Apl: Exit Function
1
5001
by: vedika | last post by:
Hello, I have problem with word-wrapping. When width is given in pixel style="word-wrap:word-break" works well but when it is given in percentage then it is not working. <table border="1" width="20%"> <tr> <td width="10%" style="word-wrap:break-word"> cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc </td> </tr> </table>
0
7936
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7874
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8366
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7997
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8227
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6646
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5738
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5402
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
1469
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.