|
|
XCIX. String functionsIntroduzione
These functions all manipulate strings in various ways. Some more
specialized sections can be found in the regular expression and
URL handling sections.
For information on how strings behave, especially with regard to
usage of single quotes, double quotes, and escape sequences, see
the Strings entry in
the Types section of the
manual.
RequisitiQueste funzioni sono disponibili nei moduli standard,
che sono sempre disponibili. InstallazioneNon � necessaria nessuna installazione per usare queste
funzioni, esse fanno parte del core di PHP. Costanti PredefiniteQuesta estensione non definisce alcuna costante. - Sommario
- addcslashes -- Quote string with slashes in a C style
- addslashes -- Quote string with slashes
- bin2hex --
Convert binary data into hexadecimal representation
- chop -- Alias of rtrim()
- chr -- Return a specific character
- chunk_split -- Split a string into smaller chunks
- convert_cyr_string --
Convert from one Cyrillic character set to another
- count_chars --
Return information about characters used in a string
- crc32 -- Calculates the crc32 polynomial of a string
- crypt -- One-way string encryption (hashing)
- echo -- Output one or more strings
- explode -- Split a string by string
- get_html_translation_table --
Returns the translation table used by
htmlspecialchars() and
htmlentities()
- get_meta_tags --
Extracts all meta tag content attributes from a file and returns
an array
- hebrev --
Convert logical Hebrew text to visual text
- hebrevc --
Convert logical Hebrew text to visual text with newline conversion
- html_entity_decode --
Convert all HTML entities to their applicable characters
- htmlentities --
Convert all applicable characters to HTML entities
- htmlspecialchars --
Convert special characters to HTML entities
- implode -- Join array elements with a string
- join -- Join array elements with a string
- levenshtein --
Calculate Levenshtein distance between two strings
- localeconv -- Get numeric formatting information
- ltrim --
Strip whitespace from the beginning of a string
- md5_file -- Calculates the md5 hash of a given filename
- md5 -- Calculate the md5 hash of a string
- metaphone -- Calculate the metaphone key of a string
- money_format -- Formats a number as a currency string
- nl_langinfo --
Query language and locale information
- nl2br --
Inserts HTML line breaks before all newlines in a string
- number_format -- Format a number with grouped thousands
- ord -- Return ASCII value of character
- parse_str -- Parses the string into variables
- print -- Output a string
- printf -- Output a formatted string
- quoted_printable_decode --
Convert a quoted-printable string to an 8 bit string
- quotemeta -- Quote meta characters
- rtrim --
Strip whitespace from the end of a string
- setlocale -- Set locale information
- sha1_file -- Calculate the sha1 hash of a file
- sha1 -- Calculate the sha1 hash of a string
- similar_text --
Calculate the similarity between two strings
- soundex -- Calculate the soundex key of a string
- sprintf -- Return a formatted string
- sscanf --
Parses input from a string according to a format
- str_pad --
Pad a string to a certain length with another string
- str_repeat -- Repeat a string
- str_replace --
Replace all occurrences of the search string with the replacement string
- str_rot13 -- Perform the rot13 transform on a string
- str_word_count --
Return information about words used in a string
- strcasecmp --
Binary safe case-insensitive string comparison
- strchr --
Find the first occurrence of a character
- strcmp -- Binary safe string comparison
- strcoll -- Locale based string comparison
- strcspn --
Find length of initial segment not matching mask
- strip_tags -- Strip HTML and PHP tags from a string
- stripcslashes --
Un-quote string quoted with addcslashes()
- stripslashes --
Un-quote string quoted with addslashes()
- stristr --
Case-insensitive strstr()
- strlen -- Get string length
- strnatcasecmp --
Case insensitive string comparisons using a "natural order"
algorithm
- strnatcmp --
String comparisons using a "natural order" algorithm
- strncasecmp --
Binary safe case-insensitive string comparison of the first n
characters
- strncmp --
Binary safe string comparison of the first n characters
- strpos --
Find position of first occurrence of a string
- strrchr --
Find the last occurrence of a character in a string
- strrev -- Reverse a string
- strrpos --
Find position of last occurrence of a char in a string
- strspn --
Find length of initial segment matching mask
- strstr -- Find first occurrence of a string
- strtok -- Tokenize string
- strtolower -- Make a string lowercase
- strtoupper -- Make a string uppercase
- strtr -- Translate certain characters
- substr_count -- Count the number of substring occurrences
- substr_replace -- Replace text within a portion of a string
- substr -- Return part of a string
- trim --
Strip whitespace from the beginning and end of a string
- ucfirst -- Make a string's first character uppercase
- ucwords --
Uppercase the first character of each word in a string
- vprintf -- Output a formatted string
- vsprintf -- Return a formatted string
- wordwrap --
Wraps a string to a given number of characters using a string
break character.
User Contributed Notes String functions |
|
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 :)
|
|
|
| |