473,898 Members | 4,033 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I change this function to add a line break ?

290 Contributor
Hi,
I am using a function called htmlwrap() which states that it
does NOT add a "<br>" to the 70 character
line so that it forces a line wrap.

( the script safely wraps long words without destroying
html tags which wordwrap has a tendency of doing! ))

What I want to do is add that line break so that it DOES force a
line wrap - but I am not sure where to insert it in the function

Can anyone suggest which line of the following function to change ?



Expand|Select|Wrap|Line Numbers
  1. /* htmlwrap() is a function which wraps HTML by breaking long words and
  2. * preventing them from damaging your layout.  This function will NOT
  3. * insert <br /> tags every "width" characters as in the PHP wordwrap()
  4. * function. 
  5. */
  6.  
  7. function htmlwrap($str, $width = 70, $break = "\n", $nobreak = "") {
  8.  
  9.   // Split HTML content into an array delimited by < and >
  10.   // The flags save the delimeters and remove empty variables
  11.   $content = preg_split("/([<>])/", $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  12.  
  13.   // Transform protected element lists into arrays
  14.   $nobreak = explode(" ", strtolower($nobreak));
  15.  
  16.   // Variable setup
  17.   $intag = false;
  18.   $innbk = array();
  19.   $drain = "";
  20.  
  21.   // List of characters it is "safe" to insert line-breaks at
  22.   // It is not necessary to add < and > as they are automatically implied
  23.   $lbrks = "/?!%)-}]\\\"':;&";
  24.  
  25.   // Is $str a UTF8 string?
  26.   $utf8 = (preg_match("/^([\x09\x0A\x0D\x20-\x7E]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$/", $str)) ? "u" : "";
  27.  
  28.   while (list(, $value) = each($content)) {
  29.     switch ($value) {
  30.  
  31.       // If a < is encountered, set the "in-tag" flag
  32.       case "<": $intag = true; break;
  33.  
  34.       // If a > is encountered, remove the flag
  35.       case ">": $intag = false; break;
  36.  
  37.       default:
  38.  
  39.         // If we are currently within a tag...
  40.         if ($intag) {
  41.  
  42.           // Create a lowercase copy of this tag's contents
  43.           $lvalue = strtolower($value);
  44.  
  45.           // If the first character is not a / then this is an opening tag
  46.           if ($lvalue{0} != "/") {
  47.  
  48.             // Collect the tag name   
  49.             preg_match("/^(\w*?)(\s|$)/", $lvalue, $t);
  50.  
  51.             // If this is a protected element, activate the associated protection flag
  52.             if (in_array($t[1], $nobreak)) array_unshift($innbk, $t[1]);
  53.  
  54.           // Otherwise this is a closing tag
  55.           } else {
  56.  
  57.             // If this is a closing tag for a protected element, unset the flag
  58.             if (in_array(substr($lvalue, 1), $nobreak)) {
  59.               reset($innbk);
  60.               while (list($key, $tag) = each($innbk)) {
  61.                 if (substr($lvalue, 1) == $tag) {
  62.                   unset($innbk[$key]);
  63.                   break;
  64.                 }
  65.               }
  66.               $innbk = array_values($innbk);
  67.             }
  68.           }
  69.  
  70.         // Else if we're outside any tags...
  71.         } else if ($value) {
  72.  
  73.           // If unprotected...
  74.           if (!count($innbk)) {
  75.  
  76.             // Use the ACK (006) ASCII symbol to replace all HTML entities temporarily
  77.             $value = str_replace("\x06", "", $value);
  78.             preg_match_all("/&([a-z\d]{2,7}|#\d{2,5});/i", $value, $ents);
  79.             $value = preg_replace("/&([a-z\d]{2,7}|#\d{2,5});/i", "\x06", $value);
  80.  
  81.             // Enter the line-break loop
  82.             do {
  83.               $store = $value;
  84.  
  85.               // Find the first stretch of characters over the $width limit
  86.               if (preg_match("/^(.*?\s)?([^\s]{".$width."})(?!(".preg_quote($break, "/")."|\s))(.*)$/s{$utf8}", $value, $match)) {
  87.  
  88.                 if (strlen($match[2])) {
  89.                   // Determine the last "safe line-break" character within this match
  90.                   for ($x = 0, $ledge = 0; $x < strlen($lbrks); $x++) $ledge = max($ledge, strrpos($match[2], $lbrks{$x}));
  91.                   if (!$ledge) $ledge = strlen($match[2]) - 1;
  92.  
  93.                   // Insert the modified string
  94.                   $value = $match[1].substr($match[2], 0, $ledge + 1).$break.substr($match[2], $ledge + 1).$match[4];
  95.                 }
  96.               }
  97.  
  98.             // Loop while overlimit strings are still being found
  99.             } while ($store != $value);
  100.  
  101.             // Put captured HTML entities back into the string
  102.             foreach ($ents[0] as $ent) $value = preg_replace("/\x06/", $ent, $value, 1);
  103.           }
  104.         }
  105.     }
  106.  
  107.     // Send the modified segment down the drain
  108.     $drain .= $value;
  109.   }
  110.  
  111.   // Return contents of the drain
  112.   return $drain;
  113. }
  114.  
  115. ?>  
Jul 15 '09 #1
7 4211
dlite922
1,584 Recognized Expert Top Contributor
Why not just use wordwrap() ?


Dan
Jul 15 '09 #2
jeddiki
290 Contributor
From my first post:

( the script safely wraps long words without destroying
html tags which wordwrap has a tendency of doing! ))
Anyone know how to insert this line break ?
Jul 15 '09 #3
dlite922
1,584 Recognized Expert Top Contributor
@jeddiki
Ya, but you continue as

What I want to do is add that line break so that it DOES force a
line wrap
So I don't get it...do you want to break HTML or not?
Jul 16 '09 #4
jeddiki
290 Contributor
This function htmlwrap() does not add a line break - that is what it says in the description - but that is exactly why I want to modify it

I want to have a line break inserted at the end of 70 characters,
unless doing so will break a html tag - it that case, keep going
until outside the tags - then insert the line break.

This function htmlwrap() is very close to what I want because it carefully
leaves the hyperlinks ( and any other html tags ) intact - it won't touch them.

Wordwrap() on the other hand can not do this - it wrecks my hyperlinks.

So what I want to do is modify this htmlwrap so that it DOES put the
line break in and force a wrap without damaging my hyperlinks.

Can you see a way to modify this function ?
Thanks
Jul 17 '09 #5
dlite922
1,584 Recognized Expert Top Contributor
Well right in the definition it gives you away to put your own type of break in instead of the default "\n"

What happens if you call the function with the third param as "<br/>" ?




Dan
Jul 17 '09 #6
jeddiki
290 Contributor
Well Dan

That is a good idea,
and to be honest, I would have been petty embarrassed
if it had worked ;-)

Although, of course I wanted it to because I want to close the problem.

Unfortunately, it did not make any difference. :(
Jul 17 '09 #7
jeddiki
290 Contributor
Hi all,

Last week I emailed the programmer who wrote this script
to see if he could help me put a line break into it
and force the wrap.

Unfortunately he has not replied, so I am still looking for a solution :(

It is not a very long script, but it is a bit too complicated for me.

Has anyone noticed how I can get my forced wrap ?

Thanks.
Jul 25 '09 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

4
2646
by: Richard Cornford | last post by:
For the last couple of months I have been trying to get the next round of updates to the FAQ underway and been being thwarted by a heavy workload (the project I am working on has to be finished an QA tested for a new year release. I don't think that going to prove practical, but there is no harm in trying :) and some serious family commitments. But it has to be done soon so this is stage one. Mike Winter provided an extensive list of...
4
1971
by: comp.lang.tcl | last post by:
I wrote this PHP function in the hopes that it would properly use a TCL proc I wrote about 4 years ago: if (!function_exists('proper_case')) { /** * Ths function will convert a string into a proper case format using the customized TCL proc "PROPER_CASE" from the included TCL string tools libraries * * @access public
3
16064
by: msnews.microsoft.com | last post by:
Hi i am using User32.dll in Visual stdio 2005. public static extern long SetActiveWindow(long hwnd); public static extern long keybd_event(byte bVk, byte bScan, long dwFlags,
13
4978
by: sonald | last post by:
Hi, Can anybody tell me how to change the text delimiter in FastCSV Parser ? By default the text delimiter is double quotes(") I want to change it to anything else... say a pipe (|).. can anyone please tell me how do i go about it?
1
6045
by: mIDO | last post by:
Hello, I have developed a script that change the font size in css, but only the attribute "font-size" on the body tag, not change the entire active stylesheet. When i click to change the size <a href="#" title="Change Font Size" onclick="cambia_font_size(2);">A</a>
1
2056
by: Sam Samson | last post by:
Greeetings All .. For my users convenience I have mapped function keys F2 .. F12 to change the tabs on the Tabcontrol. Works like a charm <ominous musicuntil one hits F8</ominous music> That particular tabpage has a webbrowser object embedded in it .. and after it flicks to that tabpage it no longer plays nice with the other Tabpages .. click on another Tab using the mouse and all is wonderful again. (unless
11
1789
by: Daniel T. | last post by:
The function below does exactly what I want it to (there is a main to test it as well.) However, I'm curious about ideas of making it better. Anyone interested in critiquing it? void formatText( const string& in, int charsPerLine, int lines, vector< string >& out ) { out.resize( 1 ); out = ""; int prev = 0;
16
4453
by: lovecreatesbea... | last post by:
It takes mu so time to finish this C source code line count function. What do you think about it? / ******************************************************************************* * Function : size_t linecnt(char *filenm); * Author : jhlicfoocbar@gmail.com, remove foobar for email * Date : 2008.4.12 * Description: C source code line count. No comments & no space lines
1
4136
by: CFFAN | last post by:
<h3>Wrap Example</h3> <cfset inputText1="Inserts line break at the location of the first white space character (such as a space, tab, or new line) before the specified limit on a line. If a line has no whitespace characters before the limit, inserts a line break at the limit. Uses the operating-system specific line break: newline for UNIX, carriage return and newline on Windows.If you specify the strip parameter, all existing line breaks are...
0
9994
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
9842
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
11267
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
10957
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
9663
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...
0
7197
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
5882
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...
1
4712
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4298
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.