|
|
XCIX. String-FunktionenEinf�hrung
Mit diesen Funktionen werden Strings (Zeichenketten) auf
verschiedene Arten ver�ndert. Spezielle Anwendungen k�nnen in
den Abschnitten zu regul�ren Ausdr�cken (regular expression)
und der URL-Handhabung gefunden werden.
Informationen zur Funktionsweise von Strings (insbesondere beim
Gebrauch von einfachen bzw. doppelten Anf�hrungszeichen und
Escape-Sequenzen) erhalten Sie unter dem
Strings-Eintrag
im Kapitel Typen des Manuals.
AnforderungenDiese Erweiterung ben�tigt zur Erstellung keine externen Bibliotheken. InstallationF�r diese Funktionen ist keine Installation erforderlich,
diese geh�ren zum Grundbestand von PHP. Vordefinierte KonstantenDiese Erweiterung definiert keine Konstanten. - Inhaltsverzeichnis
- addcslashes --
Stellt Zeichen eines Strings ein "\" voran (wie in C)
- addslashes --
Stellt bestimmten Zeichen eines Strings einen Backslash "\"
(R�ckstrich) voran
- bin2hex --
Wandelt Bin�r-Daten in ihre hexadezimale Entsprechung um
- chop -- Entfernt Leerzeichen, Tabulatoren und Zeilenvorsch�be am String-Ende
- chr -- Gibt ein einzelnes Zeichen zur�ck
- chunk_split -- Zerlegt einen String in Teile gleicher L�nge
- convert_cyr_string --
Setzt Strings von einem kyrillischen Zeichensatz in einen anderen
um
- count_chars --
Gibt Informationen �ber die in einem String enthaltenen Zeichen
zur�ck
- crc32 --
Berechnet den polynomischen CRC32-Wert eines Strings
- crypt -- DES-Verschl�sselung eines Strings
- echo -- Gibt einen oder mehrere Strings aus
- explode --
Zerteilt einen String anhand eines Trennzeichens
- fprintf -- Write a formatted string to a stream
- get_html_translation_table --
Gibt die �bersetzungs-Tabelle zur�ck, die von
htmlspecialchars() und
htmlentities() benutzt wird
- hebrev --
Konvertiert (nat�rlichen) hebr�ischen Text in sichtbaren Text
- hebrevc --
Konvertiert (nat�rlichen) hebr�ischen Text in sichtbaren Text
incl. Anpassung von Zeilenumbr�chen
- html_entity_decode --
Convert all HTML entities to their applicable characters
- htmlentities --
Wandelt alle Sonderzeichen in entsprechende HTML-Codes um
- htmlspecialchars --
Wandelt Sonderzeichen in HTML-Codes um
- implode -- Verbindet Array-Elemente zu einem String
- join -- Join verbindet Array-Elemente zu einem String
- levenshtein --
Berechnet den Levenshtein-Unterschied zweier Strings
- localeconv -- Get numeric formatting information
- ltrim --
Entfernt f�hrende Leerraum eines Strings
- md5_file -- Calculates the md5 hash of a given filename
- md5 -- Errechnet den MD5-Code eines Strings
- metaphone --
Berechnet den metaphone-Schl�ssel eines Strings
- money_format -- Formats a number as a currency string
- nl_langinfo --
Query language and locale information
- nl2br --
F�gt vor allen Zeilenumbr�chen eines Strings HTML-Zeilenumbr�che ein
- number_format -- Format a number with grouped thousands
- ord -- Gibt den ASCII-Wert eines Zeichens zur�ck
- parse_str -- �bertr�gt einen String in Variable
- print -- Ausgabe eines Strings
- printf -- Gibt einen formatierten String aus
- quoted_printable_decode --
Konvertiert einen "quoted-printable"-String in einen 8-Bit-String
- quotemeta -- Quoten von Meta-Zeichen
- rtrim -- Entfernt Leerzeichen am String-Ende
- setlocale -- Setzt lokale Informationen
- sha1_file -- Calculate the sha1 hash of a file
- sha1 -- Calculate the sha1 hash of a string
- similar_text --
Berechnet die �hnlichkeit zweier Zeichenketten
- soundex --
Berechnet die Laut-�hnlichkeit eines Strings
- sprintf -- Gibt einen formatierten String zur�ck
- sscanf --
�bertr�gt einen String in ein angegebenes Format
- str_ireplace --
Case-insensitive version of str_replace().
- str_pad --
Erweitert einen String auf eine bestimmte L�nge unter Verwendung
eines anderen Strings
- str_repeat -- Wiederholt eine String-Ausgabe
- str_replace --
Ersetzt alle Vorkommen eines Strings in einem anderen String
- str_rot13 -- Perform the rot13 transform on a string
- str_shuffle -- Randomly shuffles a string
- str_word_count --
Gibt Informationen �ber Worte in einem String zur�ck
- strcasecmp -- Bin�rer Vergleich von Zeichenketten
- strchr --
Sucht erstes Vorkommen des gesuchten Zeichens und liefert den Reststring
- strcmp -- Bin�rer Vergleich zweier Strings
- strcoll -- Locale based string comparison
- strcspn --
Ermittelt die Anzahl der nicht �bereinstimmenden Zeichen
- strip_tags --
Entfernt HTML- und PHP-Tags aus einem String
- stripcslashes -- Umkehrung / Gegenst�ck zu addcslashes
- stripos --
Find position of first occurrence of a case-insensitive string
- stripslashes -- Umkehrung / Gegenst�ck zu addslashes
- stristr --
Wie strstr(), aber ohne R�cksicht auf Gro�- bzw.
Kleinschreibung
- strlen -- Ermitteln der String-L�nge
- strnatcasecmp --
String-Vergleich "nat�rlicher Ordnung" ohne Unterscheidung der
Schreibweise
- strnatcmp --
String-Vergleich unter Verwendung einer "nat�rlichen Ordnung"
- strncasecmp --
Binary safe case-insensitive string comparison of the first n
characters
- strncmp --
Binary safe string comparison of the first n characters
- strpos --
Sucht erstes Vorkommen des Suchstrings und liefert die Position
- strrchr --
Sucht letztes Vorkommen des gesuchten Zeichens und liefert den Reststring
- strrev -- Umdrehen eines Strings
- strrpos --
Sucht letztes Vorkommen des gesuchten Zeichens und liefert die Position
- strspn --
Ermittelt die L�nge der �bereinstimmenden Zeichen
- strstr -- Sucht erstes Vorkommen des Suchstrings und liefert den Reststring
- strtok -- Zerlegt einen String
- strtolower -- Setzt einen String in Kleinbuchstaben um
- strtoupper -- Setzt einen String in Gro�buchstaben um
- strtr -- Tauscht bestimmte Zeichen aus
- substr_count --
Ermittelt, wie oft eine Zeichenkette in einem String vorkommt
- substr_replace -- Ersetzt Text in einer Zeichenkette
- substr -- Gibt einen Teil eines Strings zur�ck
- trim --
Entfernt �berfl�ssige Zeichen ("whitespace") am Anfang und Ende
eines Strings
- ucfirst --
Setzt das erste Zeichen eines Strings als Gro�buchstabe um
- ucwords --
Setzt die ersten Buchstaben aller W�rter eines Strings in die
entsprechenden Gro�buchstaben um
- vprintf -- Output a formatted string
- vsprintf -- Return a formatted string
- wordwrap --
Bricht die Zeilen eines Strings nach einer bestimmten Anzahl
Zeichen mittels des angegebenen Trennzeichens um.
User Contributed Notes String-Funktionen |
|
heiko at individual-web dot com
07-Mar-2000 03:24 |
|
I had the problem that in some of the guestbooks I programmed, people
entererd trash like 400 characters without spaces and such. Without any
spaces there was no way to break the lines and the whole guestbooked
looked screwed. I wrote this little function that makes sure no words are
more than a specified number of characters long. If a word is too long,
spaces are inserted to get the word to the maximum length allowed. Maybe
it's useful to some of you:
function strmaxwordlen($input,$len)
{
$l = 0;
$output = "";
for ($i = 0; $i <
strlen($input); $i++) {
$char = substr($input,$i,1);
if ($char
!= " ") { $l++; } else { $l = 0; }
if ($l == $len) { $l =
0; $output .= " "; }
$output .= $char;
}
return($output);
}
[Editor's note:
Alternativaly,
wordwrap() function is available for this purpose
Maxim]
|
|
mfawcett at tir dot com
24-Apr-2000 07:45 |
|
For a MySQL problem (where a user might put quotes in a text field from a
form) use addslashes() to escape all quotes (single and double). For
example:
// Assuming 'textstuff' is from a form
$mytextstuff
= addslashes($textstuff);
$sql = "insert into MyTable set
MyField='$mytextstuff'";
Also if you are working with html
forms and/or text fields from databases a lot you'll probably want to read
up on commands like htmlspecialchars() as well (a field like
"foo<bar>" might not throw MySQL off but it won't display
correctly in an html page).
|
|
ognio at peruserver dot com
21-Sep-2000 12:39 |
|
In order to properly display text from a form into an html page you need
code
like this:
<? echo
htmlentities(stripslashes($_GET['form_text'])); ?>
|
|
R dot J dot Vrijhof at bigfoot dot com
26-Dec-2000 03:20 |
|
I wanted to convert numbers to an adjective form (so from "1" to
"1st", from "352" to "352nd", etc.), but
couldn't find it in PHP, so I wrote this little code to do that for me.
Hope you find it useful:
function nth($in) {
if
(!is_long($in))
return(-1);
switch ($in) {
case 0 :
return("0th");
case 1 : return("1st");
case 2 : return("2nd");
case 3 :
return("3rd");
case 4 :
case 5 :
case 6
:
case 7 :
case 8 :
case 9 :
case 10
:
case 11 :
case 12 :
case 13 :
case 14
:
case 15 :
case 16 :
case 17 :
case 18
:
case 19 : return($in."th");
}
switch
(substr($in, -1, 1)) {
case 0 : return($in."th");
case 1 : return($in."st");
case 2 :
return($in."nd");
case 3 :
return($in."rd");
case 4 :
case 5 :
case
6 :
case 7 :
case 8 :
case 9 :
return($in."th");
default : return(0);
}
}
It will return -1 when the input is not an integer and 0
when it couldn't find a match (although that shouldn't happen).
|
|
david at audiogalaxy dot com
13-Jun-2001 08:31 |
|
Browsers (Internet Explorer at least) won't wrap text immediately before
puntuation . ? ! ( ) [ ] { } / even if the preceeding character is
whitespace. I believe this is intentional widow/orphan prevention
behavior. This complicates the processing of user-inputed text (e.g. the
message board junk problem). Even if you use <textarea wrap=hard>
to force newlines into the input text (which is imperfect since a clever
user can just modify the HTML before posting), people posting long strings
of punctuation characters, or just punctuation characters at the beginning
of each line in the <textarea> will mess up the format of the page
for users viewing their post.
You obviously can't solve this by
just inserting a spaces - the browser still won't wrap. My solution is to
use str_replace to put a (the least visually impacting
non-whitespace character I can think of) between the \n and any
pucntuation so the wrap can happen in the whitespace before the
. Kindof ironic to be using to *cause* a
break:)
[Editor's note:
You could also use wordwrap()
function
Maxim Maletsky]
|
|
thanatos at wol dot be
15-Jun-2001 10:45 |
|
I have written an *evil* little function that will cut a string on a
character given. Features:
1) Minimum length.
2) If a string
doesn't contain the character, it cuts your string to minimum
length.
3) If the next character beyond the minimumlength equals the
given character, it will cut the string to minimulength as
well.
Code:
<?php
function cuttext($tring,$cuton)
{
/* Define the character to cut on */
/* One could make an
array with all characters to cut on */
/* But I wouldn't know how to
:) */
$space=" ";
if (!strstr($tring,$space))
{
/* No space is found in the whole string: cut at 20th
character */
$tring=substr($tring,0,$cuton);
}
if
(substr($tring,$cuton,1)==$space) {
/* 21st character is a
space: cut at 20th character
*/
$tring=substr($tring,0,$cuton);
} else {
/*
21st Character is NOT a space: return to last space and cut there
*/
while ($teller <= $cuton) {
if
(substr($tring,$cuton-$teller,1)==$space)
{
$tring=substr($tring,0,$cuton-$teller);
break;
}
$teller++;
}
}
return
$tring;
}
echo(cuttext("waf groink muha zz gruu wrrreea iii
gargghhh >:)>:)",20));
?>
|
|
rs234 at cornell dot edu
04-Aug-2001 12:31 |
|
there's a problem when i used the addslashes function for my odbc
connection... in order to fix it, I used the htmlspecialchars($str_var,
ENT_QUOTES); instead and it worked fine. example is as
follow:
// $str - a string w/ single quotes
$str =
htmlspecialchars($str, ENT_QUOTES);
.
.
.
.
$sql =
"<something> $str <something>";
<etc.>
|
|
carl at _nospam_youngbloods dot org
10-Jan-2002 03:27 |
|
I've ported a function to PHP that will find the longest common substring
in two different strings. Here it is:
function
LongestCommonSubstring($string1, $string2)
{
// find length of
longest common substring first
$L = array();
$length1 =
strlen($string1);
$length2 = strlen($string2);
for ($i =
$length1; $i >= 0; $i--)
{
for ($j = $length2; $j >= 0;
$j--)
{
if ($string1[$i] == '' || $string2[$j] == '')
$L[$i][$j] = 0;
elseif ($string1[$i] == $string2[$j]) $L[$i][$j]
=
1 + $L[$i + 1][$j + 1];
else $L[$i][$j] = max($L[$i
+ 1][$j], $L[$i][$j + 1]);
}
}
// then find the
actual substring
$substring = '';
$i = 0;
$j = 0;
while ($i < $length1 && $j < $length2)
{
if
($string1[$i] == $string2[$j])
{
$substring .=
$string1[$i];
$i++; $j++;
}
elseif ($L[$i + 1][$j]
>= $L[$i][$j + 1]) $i++;
else $j++;
}
return
$substring;
}
Here is where I found the original:
|
|
albanac at gmx dot de
20-Feb-2002 08:22 |
|
I found a nice replacement vor the "swap" command, which used to
swap two variables...
it even works with more than one element and
I used it to change the bgcolor of a <table> each row (makes reading
more comfortable)
first you define $color: $color=
array('#0066CC', '#0099CC'); this piece of code just gives out another
color, each time you call it $tmp = $color[0]; $col = array_shift
($color); $color[] = $tmp;
|
|
captainbajoo at juno dot com
22-Apr-2002 12:09 |
|
This is a more compact function to get a numeric adjective. No idea if
it's faster than the other "nth" function here (though probably
is, since "th" is more likely to occur), but the code is
definitely shorter.
Assumes integer input. Returns a
string.
function getNth ($n) { $qn = (int) (($n%100) /
10); $rn = $n % 10;
$suffix = "th";
if
($qn != 1) { switch ($rn) { case 1: $suffix =
"st"; break; case 2: $suffix = "nd"; break;
case 3: $suffix = "rd"; break; } }
return $n . $suffix; }
|
|
jewfish at jewfish dot net
05-Jun-2002 06:20 |
|
One could make an ever quicker isalphanumeric() function by using regular
expressions:
function isalphanumeric($test) { return
!(preg_match("/[^a-z,A-Z,0-9 ]/", $test)); }
Note:
that is a space after the 9, in order to inclue spaces in the comparison.
One could also add \t and \n so that it did not fail out if it found a tab
or newline. This is much cleaner and more efficient than the array
approach described earlier, and nicer than the ordinal characters approach
as well.
|
|
chris at earleweb_nospam dot com
13-Jul-2002 09:03 |
|
An alternative to the the "array_shift" way to change $color
array:
$Counter = 0; //set to 1 if you want to start on
#CCCCCC $Colors = Array('#FFFFFF', '#CCCCCC'); $tableColor =
$Colors[($Counter %= 2)]; /* $Counter %= 2; ensures $Counter is never
greater than 1, in the off chance that you have a 32 thousand element
array and really is not needed -- you could use $Counter % 2 if you really
want to*/ $Counter++;
When ever $Counter is odd the modulus
division will leave 1, but even numbers (and 0) mod 2 = 0. Then Counter
is added to so that the next phase of the loop will become the next color.
|
|
dr dot helga at prickel-pit dot de
14-Jul-2002 02:41 |
|
For generating a Field-Number File I needed a function, wich can add chars
in front or at the end of a string to match a certain string length. I
couldn't find it in php so here's the function I wrote to solve the
problem:
--------------CUT------------------ function
addChars($string,$char,$endlength,$dir)
{ $i=0; $stringlength=strlen($string); $addchar_lenght=$endlength-$stringlength; $addchar_string=""; while
($i<$addchar_lenght)
{ $addchar_string.=$char; $i++; } if ($dir==1)
{ $new_string=$string.$addchar_string; } if ($dir==0)
{ $new_string=$addchar_string.$string; } return
$new_string; } ----------------/CUT-----------------
$string
is the original string $char is the character which shall be
added $endlength is the length of the new string $dir specifies if
the chars shall be added in front (0) or at the end (1) of the
string
example: "1234" should be
"00001234":
$text1="1234"; $text2=addChars($text,"0",8,0)
hope
someone will find it usefull ...
|
|
bog2k<AT>softhome<DOT>net
18-Jul-2002 04:02 |
|
How about reversing the HTML Chars (é => �). Here is a
function that is able to reverse any of HTML entitities regardles if the
entity has the ";" termination. That means it can detect and
replace "télé" => "t�l�", and
also "télé" =>
"t�l�".
function ReverseHtmlChars ($str, $trans_table =
HTML_ENTITIES) {
$trans = get_html_translation_table
($trans_table); $trans2 = preg_replace ("';$'",
"", $trans); $trans = array_flip ($trans); $trans2
= array_flip ($trans2);
return strtr (strtr ($str, $trans),
$trans2); }
Also you can provide a second argument if you only
want to replace the HTML specialchars.
I've read a note of the
Editor in which he said that this is kinda pointless because normally you
don't need to reverse HTML chars ... well, thats partially true.
In my case I really needes something like this because this way I
can strip a html file of tags, reverse all HTML entities and obtain a very
*human readable* text file !!! ... so its not so pointless.
P.S.
you can also think of a similar function that has as second argument the
translation table rather than 0/1 so you can have your own set of
translations (very very useful for text
translations)
Cheers, BoG
|
|
global2b at yahoo dot com
21-Aug-2002 04:25 |
|
In case any of you wanted to parse a deliminated text file, I've come up
with a script that may of some use.
//I call the function and
return the parsed data in a multi-D array.
function thisone()
{ $info =
array(); $x=file("yourData.txt");
//Here I take the
first line of the data file and grab the variable names. $names =
explode('|',$x[0]);
//Once I've got the variable names I delete
x[0] so that I can run through the info array with
foreach unset($x[0]); foreach($x as $keyx=>$valuex)
{ $w = explode('|',$valuex); foreach($w as
$keyw=>$valuew) { $info[$keyx][$names[$keyw]] =
$valuew; } } return $info; }
$bin =
thisone(); print_r($bin);
|
|
skip at seawana dot com
29-Aug-2002 10:24 |
|
// Here is a simpler way to swap two values (for alternating TABLE row
colors for instance). // Define your colors in an array: $ar_colors
= array ("#0066AA","#003399");
// Now simply
display them and then reverse the array like this: echo $ar_colors[0];
$ar_colors = array_reverse($ar_colors);
|
|
d dot gebuehr at ntz dot de
13-Sep-2002 10:25 |
|
I've written a small function, which extracts all positions of a given
character from a string. It may be useful for example to modify html-tags
with not known values. (It's used to get rid of class-arguments and
mso-styles while importing MS-Word-Documents):
function
charpos($searchstring,$delimiter) {
global $positions;
global
$search_found;
if (strpos($searchstring,$delimiter) === FALSE) {
$search_found=0;
}
else {
$search_found=1;
$searchlen=strlen($searchstring);
for
($i_s=0;$i_s<$searchlen;$i_s++){if
(substr($searchstring,$i_s,1)==$delimiter){$positions[]=$i_s; }
}
}
}
You can work with the positions-array, but remember
to unset it before calling the function again, otherwise you'll fill it
more and more :-)
Counting of positions begins with 0. If the
charakter you search for ist not to be found in your searchstring, the
function returns $search_found=0, otherwise $search_found will be
1.
If typing the function, be sure to have three "=" in
asking whether the charakter was found.
|
|
discord at mac dot com
23-Oct-2002 11:30 |
|
If you are outputting to html, it might be better to insert a wordbreak
(<wbr>) tag to allow a linebreak. If the text is too long and needs
to be wrapped, the browser will break the line at that tag, otherwise, it
ignores it. This is good because it won't even show up as a space if the
browser doesn't wrap it at that point.
Here's an optimised
preg_replace version of the strmaxwordlen function that uses this
tag:
function splitLongWords($text, $max) { ����return
preg_replace( '/([^\s]{'.$max.'})(?=[^\s])/', '$1<wbr>',
$text); }
(note: I didn't test this thoroughly, it may need some
work :)
|
|
webmaster at gamequbed dot com
01-Feb-2003 10:14 |
|
I was recently working on a template engine, and i found that i wanted to
add parameters to my template includes, for example,
{SUBJECTFIELD
template="LINK_ROW" class="subjectfield"}
I
found that this code worked out quite well! It converts the string into
$fileParam["SUBJECTFIELD"]["template"]
which will print
"LINK_ROW". It also works for
multiple blocks. Have fun!
$text = " {SUBJECTFIELD
class=\"alternate\"
rowtemplate=\"LINK_ROW\"} {BODYFIELD
class=\"alternate2\"
rowtemplate=\"LINK_ROW\"}";
## remove
quotes $text =
str_replace("\"","",$text);
## set
counter $counter = 0;
for
($i=0;$i<strlen($text);$i++) { ## convert each {...} block into
an array element if ($text[$i] ==
"{") { $currentEndBrace =
strpos($text,"}");
$param[$counter] =
substr($text,$i,$currentEndBrace);
## remove the end
brace $text[$currentEndBrace] =
"";
$counter++; } }
$fileParam =
array();
for ($j=0;$j<count($param);$j++) { ## remove
trailing stuff $param[$j] = rtrim($param[$j]);
## and the
braces $param[$j] =
ereg_replace("{","",$param[$j]); $param[$j] =
ereg_replace("}","",$param[$j]);
## get the
name of the template $tempIdent =
substr($param[$j],0,strpos($param[$j]," "));
## get the
rest of the vars $param[$j] =
substr($param[$j],strpos($param[$j]," ")+1);
## make a
new array $fileParam[$tempIdent] =
$param[$j]; }
while(list($key,$val) =
each($fileParam)) { ## set up as a query string $val =
str_replace(" ","&",$val);
## parse it to
a new array parse_str($val,$eachVal);
## and assign it to
another array $fileParam[$key] = $eachVal; }
|
|
tcn at pandora dot be
11-Feb-2003 10:39 |
|
Hi, I was searching for an option to extract the contents of a string
between for example [a] and [b]. I was unable to find it, so I created
something myself:
function str_extract
($String,$CharBegin,$CharEnd) { $StringLength=strlen($String); $Begin=strpos($String,$CharBegin); $End=strpos($String,$CharEnd)-$Begin+strlen($CharEnd); return
substr ($String, $Begin, $End); }
It works like this:
str_extract (string haystack, string begin, string end);
For
example: echo str_extract ("Bla bla [a]foo[b] bla bla",
"[a]","[b]"); Would produce: [a]foo[b]
Hopes
this helpes someone!!!
|
|
kop at meme dot com
06-Mar-2003 11:49 |
|
function standardize_eol($s) { /* Return text with Unix end of line
conventions. * * Input: $s The string to convert. *
* Returns: The string with Unix end of line conventions. * *
Side Effects: none */ return
strtr(ereg_replace("\r\n", "\n", $s), "\r",
"\n"); }
To do the same thing to a file:
//
Copy file, converting // Windoze and mac eol sequences to Unix eol
along the way. exec("sed -e 's/\r\$//' $old_path"
. ' | tr "\\r" "\\n"' . "
> $new_path");
Do _not_ try to set $old_path and $new_path
to the same file. Failure will be erratic.
|
|
missnglnk at missnglnk dot com
24-Mar-2003 04:35 |
|
Here's a better function to get the numerical thingy (1st, 2nd, 3rd,
etc):
function nth ($n) { $rn = $n{strlen($n)};
switch ($rn) { case 1: $suffix = "st"; break;
case 2: $suffix = "nd"; break; case 3: $suffix =
"rd"; break; default: $suffix = "th"; break;
} return $n . $suffix; }
|
|
szeryf at negativeIQ dot pl
01-Apr-2003 09:41 |
|
This is a little function I wrote for shortening strings to some arbitrary
length. It may be useful if you want to display only headlines (or just a
few starting sequences) of a larger text. The text is shortened to the
last white space character before $len chars and an ellipsis (...) is
added at the end. If no white space is found, the first $len chars (and
...) are returned. So the maximal length of returned value is always $len
+ 3. Here it goes:
function shorten ($var, $len = 120) {
if (empty ($var)) { return "";
} if (strlen ($var) < $len) { return
$var; } if (preg_match
("/(.{1,$len})\s/", $var, $match)) { return
$match [1] . "..."; } else {
return substr ($var, 0, $len) . "...";
} }
It should be pretty self-explanatory. The regular expression
matches up to $len chars followed by a white space char (\s). The match is
"greedy", so it always tries to match "as many as
possible".
|
|
|
| |