String functions
These functions all manipulate strings in various ways. Some more specialized sections can be found in the regular expression and URL handling sections.
String functions
AddSlashes
Name
AddSlashes — quote string with slashes
Description
string addslashes(string str);
Chop
Chr
Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the null byte).
See also stripslashes and quotemeta.
Name
Chop — remove trailing whitespace
Description
string chop(string str);
Returns the argument string without trailing whitespace.
Example 1. chop() example
$trimmed = Chop($line);
See also trim.
Name
Chr — return a specific character
Description
string chr(int ascii);
Returns a one-character string containing the character specified by ascii.
Example 1. chr() example
$str .= chr(27); /* add an escape character at the end of $str */
/* Often this is more useful */
$str = sprintf("The string ends in escape: %c", 27);
This function complements ord. See also sprintf with a format string of %c.
convert_cyr_string
Name
convert_cyr_string — Convert from one Cyrillic character set to another
Description
string convert_cyr_string(string str, string from, string to);
This function converts the given string from one Cyrillic character set to another. The from and to arguments are single characters that represent the source and target Cyrillic character sets. The supported types are:
-
k - koi8-r
-
w - windows-1251
-
i - iso8859-5
-
a - x-cp866
-
d - x-cp866
-
m - x-mac-cyrillic
crypt
echo
Name
crypt — DES-encrypt a string
Description
string crypt(string str, string [salt]);
crypt will encrypt a string using the standard Unix DES encryption method. Arguments are a string to be encrypted and an optional two-character salt string to base the encryption on. See the Unix man page for your crypt function for more information.
If the salt argument is not provided, it will be randomly generated by PHP.
Some operating systems support more than one type of encryption. In fact, sometimes the standard DES encryption is replaced by an MD5 based encryption algorithm. The encryption type is triggered by the salt argument. At install time, PHP determines the capabilities of the crypt function and will accept salts for other encryption types. If no salt is provided, PHP will auto-generate a standard 2-character DES salt by default unless the default encryption type on the system is MD5 in which case a random MD5- compatible salt is generated.
There is no decrypt function, since crypt uses a one-way algorithm.
Name
echo — output one or more strings
Description
echo(string arg1, string [argn]...);
Outputs all parameters.
See also: print printf flush
explode
Name
explode — split a string by string
Description
flush
array explode(string separator, string string);
Returns an array of strings containing the elements separated by separator.
Example 1. explode() example
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
See also split and implode.
Name
flush — flush the output buffer
Description
void flush(void);
Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc.) This effectively tries to push all the output so far to the user's browser.
htmlspecialchars
Name
htmlspecialchars — Convert special characters to HTML entities.
Description
string htmlspecialchars(string string);
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with these conversions made.
At present, the translations that are done are:
-
'&' (ampersand) becomes '&'
-
'"' (double quote) becomes '"'
-
'<' (less than) becomes '<'
-
'>' (greater than) becomes '>'
Note that this functions does not translate anything beyond what is listed above. For full entity translation, see htmlentities.
See also htmlentities and nl2br.
htmlentities
Name
htmlentities — Convert all applicable characters to HTML entities.
Description
string htmlentities(string string);
This function is identical to htmlspecialchars in all ways, except that all characters which have HTML entity equivalents are translated into these entities.
At present, the ISO-8859-1 character set is used. See also htmlspecialchars and nl2br.
implode
Name
implode — join array elements with a string
Description
string implode(array pieces, string glue);
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
join
ltrim
Example 1. implode() example
$colon_separated = implode($array, ":");
See also explode, join, and split.
Name
join — join array elements with a string
Description
string join(array pieces, string glue); join is an alias to implode, and is identical in every way.
Name
ltrim — Strip whitespace from the beginning of a string.
Description
string ltrim(string str);
This function strips whitespace from the start of a string and returns the stripped string. See also chop and trim.
md5
nl2br
Ord
Name
md5 — calculate the md5 hash of a string
Description
string md5(string str);
Calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm.
Name
nl2br — Converts newlines to HTML line breaks.
Description
string nl2br(string string);
Returns string with '<BR>' inserted before all newlines. See also htmlspecialchars and htmlentities.
Name
Ord — return ASCII value of character
Description
int ord(string string);
Returns the ASCII value of the first character of string. This function complements chr.
Example 1. ord() example
if (ord($str) == 10) {
echo("The first character of \$str is a line feed.\n");
}
See also chr.
parse_str
Name
parse_str — parses the string into variables
Description
void parse_str(string str);
Parses str as if it were the query string passed via an URL and sets variables in the current scope.
Example 1. Using parse_str
$str = "first=value&second[]=this+works&second[]=another"; parse_str($str);
echo $first; /* prints "value" */
echo $second[0]; /* prints "this works" */ echo $second[1]; /* prints "another" */
printf
Name
print — output a string
Description
print(string arg);
Outputs arg.
See also: echo printf flush
Name
printf — output a formatted string
Description
int printf(string format, mixed [args]...);
Produces output according to format, which is described in the documentation for sprintf. See also: print, sprintf, and flush.
quoted_printable_decode
Name
quoted_printable_decode — Convert a quoted-printable string to an 8 bit string
Description
string quoted_printable_decode(string str);
This function returns an 8-bit binary string corresponding to the decoded quoted printable string. This function is similar to imap_qprint, except this one does not require the IMAP module to work.
QuoteMeta
Name
QuoteMeta — quote meta characters
Description
int quotemeta(string str);
Returns a version of str with a backslash character (\) before every character that is among these:
. \\ + * ? [ ^ ] ( $ )
See also addslashes, htmlentities, htmlspecialchars, and nl2br.
rawurldecode
Name
rawurldecode — decode URL-encoded strings
Description
string rawurldecode(string str);
Returns a string in which the sequences with percent (%) signs followed by two hex digits have been replaced with literal characters. For example, the string
foo%20bar%40baz
decodes into
foo bar@baz
See also rawurlencode.
rawurlencode
Name
rawurlencode — URL-encode according to RFC1738
Description
string rawurlencode(string str);
Returns a string in which all non-alphanumeric characters except
-_.
have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in RFC1738 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URL's from being mangled by transmission media with character conversions (like some email systems). For example, if you want to include a password in an ftp url:
Example 1. rawurlencode() example 1
echo '<A HREF="ftp://user:', rawurlencode ('foo @+%/'), '@ftp.my.com/x.txt">';
Or, if you pass information in a path info component of the url:
Example 2. rawurlencode() example 2
echo '<A HREF="http://x.com/department_list_script/',
rawurlencode ('sales and marketing/Miami'), '">';
See also rawurldecode.
setlocale
Name
setlocale — set locale information
Description
string setlocale(string category, string locale);
category is a string specifying the category of the functions affected by the locale setting:
-
LC_ALL for all of the below
-
LC_COLLATE for string comparison - not currently implemented in PHP
-
LC_CTYPE for character classification and conversion, for example
strtoupper
-
LC_MONETARY for localeconv() - not currently implemented in PHP
-
LC_NUMERIC for decimal separator
-
LC_TIME for date and time formatting with strftime
If locale is the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories, or from "LANG".
If locale is zero or "0", the locale setting is not affected, only the current setting is returned.
Setlocale returns the new current locale, or false if the locale functionality is not implemented in the plattform, the specified locale does not exist or the category name is invalid. An invalid category name also causes a warning message.
soundex
Name
soundex — calculate the soundex key of a string
Description
string soundex(string str);
Calculates the soundex key of str.
Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter.
This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.
Example 1. Soundex Examples
soundex("Euler") == soundex("Ellery") == 'E460'; soundex("Gauss") == soundex("Ghosh") == 'G200'; soundex("Knuth") == soundex("Kant") == 'H416'; soundex("Lloyd") == soundex("Ladd") == 'L300'; soundex("Lukasiewicz") == soundex("Lissajous") == 'L222';
sprintf
Name
sprintf — return a formatted string
Description
sprintf(string format, mixed [args]...);
Returns a string produced according to the formatting string format.
The format string is composed by zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf and printf
Each conversion specification consists of these elements, in order:
-
An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.
-
An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.
-
An optional number, a width specifier that says how many characters (minimum) this conversion should result in.
-
An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than double.
-
A type specifier that says what type the argument data should be
treated as. Possible types:
a literal percent character. No argument is required.
the argument is treated as an integer, and presented as a binary number.
the argument is treated as an integer, and presented as the character with that ASCII value. the argument is treated as an integer, and presented as a decimal number.
the argument is treated as a double, and presented as a floating-point number. the argument is treated as an integer, and presented as an octal number.
the argument is treated as and presented as a string.
the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).
See also: printf
Examples
Example 1. sprintf: zero-padded integers
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
strchr
Name
strchr — Find the first occurrence of a character.
Description
string strchr(string haystack, string needle);
This function is an alias for strstr, and is identical in every way.
strcmp
Name
strcmp — binary safe string comparison
Description
int strcmp(string str1, string str2);
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. Note that this comparison is case sensitive.
See also ereg, substr, and strstr.
strcspn
Name
strcspn — find length of initial segment not matching mask
Description
int strcspn(string str1, string str2);
Returns the length of the initial segment of str1 which does not contain any of the characters in str2. See also strspn.
StripSlashes
Name
StripSlashes — un-quote string quoted with addslashes
Description
strlen
string stripslashes(string str);
Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes are made into a single backslash.
See also addslashes.
Name
strlen — get string length
Description
int strlen(string str);
Returns the length of string.
strrpos
Name
strrpos — Find position of last occurrence of a char in a string.
Description
string strrpos(string haystack, char needle);
Returns the numeric position of the last occurrence of needle in the haystack string. Note that the needle in this case can only be a single character. If a string is passed as the needle, then only the first character of that string will be used.
If needle is not found, returns false.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. See also strpos, strrchr, substr, and strstr.
strpos
Name
strpos — Find position of first occurrence of a string.
Description
string strpos(string haystack, string needle, int [offset]);
Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the
strrpos, this function can take a full string as the needle parameter and the entire string will be used. If needle is not found, returns false.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the the beginning of haystack.
See also strrpos, strrchr, substr, and strstr.
strrchr
Name
strrchr — Find the last occurrence of a character in a string.
Description
string strrchr(string haystack, string needle);
This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.
Returns false if needle is not found.
If needle is not found, false is returned.
If needle contains more than one character, the first is used.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
Example 1. strrchr() example
// get last directory in $PATH
$dir = substr( strrchr( $PATH, ":" ), 1 );
// get everything after last newline
$text = "Line 1\nLine 2\nLine 3";
$last = substr( strrchr( $text, 10 ), 1 );
strrev
See also substr and strstr.
Name
strrev — Reverse a string.
Description
string strrev(string string);
Returns string, reversed.
strcspn
Name
strcspn — find length of initial segment matching mask
Description
strstr
strtok
int strspn(string str1, string str2);
Returns the length of the initial segment of str1 which consists entirely of characters in str2. See also strcspn.
Name
strstr — Find first occurrence of a string.
Description
string strstr(string haystack, string needle);
Returns all of haystack from the first occurrence of needle to the end. If needle is not found, returns false.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. See also strrchr, substr, and ereg.
Name
strtok — tokenize string
Description
string strtok(string arg1, string arg2);
strtok() is used to tokenize a string. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.
Example 1. strtok() example
$string = "This is an example string";
$tok = strtok($string," "); while($tok) {
echo "Word=$tok<br>";
$tok = strtok(" ");
}
Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.
See also split and explode.
strtolower
Name
strtolower — Make a string lowercase.
Description
string strtolower(string str);
Returns string with all alphabetic characters converted to lowercase.
Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.
See also strtoupper and ucfirst.
strtoupper
Name
strtoupper — Make a string uppercase.
Description
string strtoupper(string string);
Returns string with all alphabetic characters converted to uppercase.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.
See also strtolower and ucfirst.
strtr
Name
strtr — Translate certain characters.
Description
string strtr(string str, string from, string to);
This function operates on str, translating all occurrences of each character in from to the corresponding character in to and returning the result.
If from and to are different lengths, the extra characters in the longer of the two are ignored.
Example 1. strtr() example
$addr = strtr($addr, "äåö", "aao");
See also ereg_replace.
substr
Name
substr — Return part of a string.
Description
string substr(string string, int start, int [length]);
Substr returns the portion of string specified by the start and length parameters.
If start is positive, the returned string will start at the start'th character of string. Examples:
$rest = substr("abcdef", 1); // returns "bcdef"
$rest = substr("abcdef", 1, 3); // returns "bcd"
If start is negative, the returned string will start at the start'th character from the end of string. Examples:
$rest = substr("abcdef", -1); // returns "f"
$rest = substr("abcdef", -2); // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
If length is given and is positive, the string returned will end length characters from start. If this would result in a string with negative length, then the returned string will contain the single character at start.
If length is given and is negative, the string returned will end length characters from the end of string. If this would result in a string with negative length, then the returned string will contain the single character at start. Examples:
trim
$rest = substr("abcdef", -1, -1); // returns "bcde"
See also strrchr and ereg.
Name
trim — Strip whitespace from the beginning and end of a string.
Description
string trim(string str);
This function strips whitespace from the start and the end of a string and returns the stripped string. See also chop and ltrim.
ucfirst
Name
ucfirst — Make a string's first character uppercase
Description
string ucfirst(string str);
Capitalizes the first character of str if that character is alphabetic.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.
See also strtoupper and strtolower.
ucwords
Name
ucwords — Uppercase the first character of each word in a string
Description
string ucwords(string str);
Capitalizes the first character of each word in str if that character is alphabetic. See also strtoupper, strtolower and ucfirst.