473,889 Members | 1,352 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 6159
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
23337
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
4220
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
72721
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
6752
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
6948
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
12459
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
4650
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
7092
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
5030
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
9805
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
11188
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10887
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
9603
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
7991
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
7148
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();...
0
5825
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6025
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4249
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.