String Functions
String Functions
substr Return part of a string. Returns the portion substr ( string $string , int $start [, int $length ] ) : string
of string specified by the start and length
parameters. echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', -1, 1); // f
- If start is non-negative, the returned string echo substr('abcdef', 7, 1); // FALSE
will start at the start'th position in string, echo substr('abcdef', 0, 4); // abcd
counting from zero. echo substr("abcdef", 1, -4); // b
- If start is negative, the returned string will echo substr("abcdef", 1, 0); // FALSE
start at the start'th character from the end echo substr('abcdef', 1); // bcdef
of string.
- If string is less than start characters long,
FALSE will be returned.
- If length is given and is positive, the string
returned will contain at most length
characters beginning from start
- If length is given and is negative, then that
many characters will be omitted from the
end of string
- If length is given and is 0, FALSE or
NULL, an empty string will be returned.
- If length is omitted, the substring starting
from start until the end of the string will be
returned.
addcslashes Quote string with slashes in a C style addcslashes ( string $str , string $charlist ) : string
stripcslashes Un-quote string quoted with addcslashes() stripcslashes ( string $str ) : string
1
preg_quote Quote regular expression characters. preg_quote ( string $str [, string $delimiter = NULL ] ) : string
preg_quote() takes str and puts a
backslash in front of every character that is
part of the regular expression syntax. This
is useful if you have a run-time string that
you need to match in some text and the
string may contain special regex
characters.
The special regular expression characters
are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - #
rtrim/chop[Alias] Strip whitespace (or other characters) from rtrim ( string $str [, string $character_mask ] ) : string
the end of a string
chunk_split Split a string into smaller chunks chunk_split ( string $body [, int $chunklen = 76 [, string $end = "\r\n" ]] ) :
string
count_chars Return information about characters used count_chars ( string $string [, int $mode = 0 ] ) : mixed
in a string
htmlentities Convert all applicable characters to HTML htmlentities ( string $string [, int $flags = ENT_COMPAT |
entities. This function is identical to ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool
htmlspecialchars() in all ways, except with $double_encode = TRUE ]]] ) : string
htmlentities(), all characters which have
HTML character entity equivalents are
translated into these entities.
htmlspecialchars Convert special characters [&,”,’,<,>] to htmlspecialchars ( string $string [, int $flags = ENT_COMPAT |
HTML entities ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool
$double_encode = TRUE ]]] ) : string
html_entity_decode Convert HTML entities to their html_entity_decode ( string $string [, int $flags = ENT_COMPAT |
2
corresponding characters ENT_HTML401 [, string $encoding = ini_get("default_charset") ]] ) :
string
htmlspecialchars_de Convert special HTML entities back to htmlspecialchars_decode ( string $string [, int $flags = ENT_COMPAT |
code characters ENT_HTML401 ] ) : string
strip_tags Strip HTML and PHP tags from a string strip_tags ( string $str [, mixed $allowable_tags ] ) : string
implode/join[Alias] Join array elements with a string implode ( string $glue , array $pieces ) : string
implode ( array $pieces ) : string
levenshtein Calculate Levenshtein distance between levenshtein ( string $str1 , string $str2 ) : int
two strings. The minimal number of
characters you have to replace, insert or levenshtein ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int
delete to transform str1 into str2. $cost_del ) : int
similar_text Calculate the similarity between two strings similar_text ( string $first , string $second [, float &$percent ] ) : int
$sim = similar_text('bafoobar', 'barfoo', $perc);
echo "similarity: $sim ($perc %)\n";
//similarity: 5 (71.428571428571 %)
number_format Format a number with grouped thousands number_format ( float $number [, int $decimals = 0 ] ) : string
number_format ( float $number , int $decimals = 0 , string $dec_point =
"." , string $thousands_sep = "," ) : string
parse_str Parses the string into variables. Using this parse_str ( string $encoded_string [, array &$result ] ) : void
function without the result parameter is
highly DISCOURAGED and $str = "first=value&arr[]=foo+bar&arr[]=baz";
DEPRECATED as of PHP 7.2.
// Recommended
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
3
quotemeta Quote meta characters. Returns a version quotemeta ( string $str ) : string
of str with a backslash character (\) before $str = "Hello world. (can you hear me?)";
every character that is among these: echo quotemeta($str);
.\+*?[^]($) Hello world\. \(can you hear me\?\)
sprintf Return a formatted string sprintf ( string $format [, mixed $... ] ) : string
sscanf Parses input from a string according to a sscanf ( string $str , string $format [, mixed &$... ] ) : mixed
format list($month, $day, $year) = sscanf("January 01 2000", "%s %d %d");
str_getcsv Parse a CSV string into an array str_getcsv ( string $input [, string $delimiter = "," [, string $enclosure = '"'
[, string $escape = "\\" ]]] ) : array
str_replace Replace all occurrences of the search str_replace ( mixed $search , mixed $replace , mixed $subject [, int
string with the replacement string &$count ] ) : mixed
str_ireplace Case-insensitive version of str_replace() str_ireplace ( mixed $search , mixed $replace , mixed $subject [, int
&$count ] ) : mixed
substr_replace Replace text within a portion of a string substr_replace ( mixed $string , mixed $replacement , mixed $start [,
mixed $length ] ) : mixed
preg_replace Perform a regular expression search and preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [,
replace int $limit = -1 [, int &$count ]] ) : mixed
preg_filter Perform a regular expression search and preg_filter ( mixed $pattern , mixed $replacement , mixed $subject [, int
replace. preg_filter() is identical to $limit = -1 [, int &$count ]] ) : mixed
preg_replace() except it only returns the
(possibly transformed) subjects where
there was a match.
preg_replace_callba Perform a regular expression search and preg_replace_callback ( mixed $pattern , callable $callback , mixed
ck replace using a callback. The behavior of $subject [, int $limit = -1 [, int &$count [, int $flags = 0 ]]] ) : mixed
this function is almost identical to
preg_replace(), except for the fact that
4
instead of a replacement parameter, one
should specify a callback.
preg_replace_callba Perform a regular expression search and preg_replace_callback_array ( array $patterns_and_callbacks , mixed
ck_array replace using callbacks. The behavior of $subject [, int $limit = -1 [, int &$count [, int $flags = 0 ]]] ) : mixed
this function is similar to
preg_replace_callback(), except that
callbacks are executed on a per-pattern
basis.
strtr Translate characters or replace substrings. strtr ( string $str , string $from , string $to ) : string
If given three arguments, this function strtr ( string $str , array $replace_pairs ) : string
returns a copy of str where all occurrences
of each (single-byte) character in from have $trans = array("h" => "-", "hello" => "hi", "hi" => "hello");
been translated to the corresponding echo strtr("hi all, I said hello", $trans);
character in to. //hello all, I said hi
If given two arguments, the second should
be an array in the form array('from' => 'to',
...). The return value is a string where all
the occurrences of the array keys have
been replaced by the corresponding
values.
str_pad Pad a string to a certain length with another str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int
string. Since the default pad_type is $pad_type = STR_PAD_RIGHT ]] ) : string
STR_PAD_RIGHT. using
STR_PAD_BOTH were always favored in str_pad("input", 10, "pp", STR_PAD_BOTH ); // ppinputppp
the right pad if the required number of
padding characters can't be evenly divided.
str_rot13 Perform the rot13 transform on a string str_rot13 ( string $str ) : string
str_rot13('PHP 4.3.0'); // CUC 4.3.0
5
str_shuffle Randomly shuffles a string str_shuffle ( string $str ) : string
str_split Convert a string to an array str_split ( string $string [, int $split_length = 1 ] ) : array
preg_split Split string by a regular expression preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags =
0 ]] ) : array
str_word_count Return information about words used in a str_word_count ( string $string [, int $format = 0 [, string $charlist ]] ) :
string mixed
strcmp Binary safe string comparison. Returns < 0 strcmp ( string $str1 , string $str2 ) : int
if str1 is less than str2; > 0 if str1 is greater
than str2, and 0 if they are equal.
strncmp Binary safe string comparison of the first n strncmp ( string $str1 , string $str2 , int $len ) : int
characters echo strncmp("phpaaa", "php", 3); // 0
echo strcmp("phpaaa", "php"); // 3
substr_compare Binary safe comparison of two strings from substr_compare ( string $main_str , string $str , int $offset [, int $length
an offset, up to length characters. [, bool $case_insensitivity = FALSE ]] ) : int
Compares main_str from position offset
with str up to length characters.
strcasecmp Binary safe case-insensitive string strcasecmp ( string $str1 , string $str2 ) : int
comparison
strncasecmp Binary safe case-insensitive string strncasecmp ( string $str1 , string $str2 , int $len ) : int
comparison of the first n characters.
strnatcmp String comparisons using a "natural order" strnatcmp ( string $str1 , string $str2 ) : int
algorithm.
Standard string comparison
Array
(
[0] => img1.png
6
[1] => img10.png
[2] => img12.png
[3] => img2.png
)
strnatcasecmp Case insensitive string comparisons using strnatcasecmp ( string $str1 , string $str2 ) : int
a "natural order" algorithm
strcoll Locale based string comparison. This strcoll ( string $str1 , string $str2 ) : int
comparison is case sensitive, and unlike
strcmp() this function is not binary safe.
strstr/strchr[Alias] Find the first occurrence of a string strstr ( string $haystack , mixed $needle [, bool $before_needle =
FALSE ] ) : string
stristr Case-insensitive strstr() stristr ( string $haystack , mixed $needle [, bool $before_needle =
FALSE ] ) : string
strrchr Find the last occurrence of a character in a strrchr ( string $haystack , mixed $needle ) : string
string
strcspn Find length of initial segment not matching strcspn ( string $subject , string $mask [, int $start [, int $length ]] ) : int
mask $a = strcspn('abcd', 'apple'); // int(0)
$b = strcspn('abcd', 'banana'); // int(0)
$c = strcspn('hello', 'l'); // int(2)
$d = strcspn('hello', 'world'); // int(2)
7
strspn Finds the length of the initial segment of a strspn ( string $subject , string $mask [, int $start [, int $length ]] ) : int
string consisting entirely of characters strspn("42 is the answer to the 128th question.", "1234567890");
contained within a given mask will assign 2 to $var, because the string "42" is the initial segment of
subject that consists only of characters contained within "1234567890".
strpos Find the position of the first occurrence of a strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int
substring in a string
stripos Find the position of the first occurrence of a stripos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int
case-insensitive substring in a string
strrpos Find the position of the last occurrence of a strrpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int
substring in a string
strripos Find the position of the last occurrence of strripos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int
a case-insensitive substring in a string
strpbrk Search a string for any of a set of strpbrk ( string $haystack , string $char_list ) : string
characters $text = 'This is a Simple text.';
// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');
strtok Tokenize string. strtok() splits a string (str) strtok ( string $str , string $token ) : string
into smaller strings (tokens), with each strtok ( string $token ) : string
token being delimited by any character
from token. That is, if you have a string like $string = "This is an example string";
"This is an example string" you could $tok = strtok($string, " ");
tokenize this string into its individual words while ($tok !== false) {
by using the space character as the token. echo $tok . PHP_EOL;
$tok = strtok(" ");
8
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 This
keeps track of where it is in the current is
string. an
example
string
explode Split a string by a string explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ]
) : array
substr_count Count the number of substring occurrences substr_count ( string $haystack , string $needle [, int $offset = 0 [, int
$length ]] ) : int
printf Output a formatted string printf ( string $format [, mixed $... ] ) : int
vprintf Output a formatted string. Operates as vprintf ( string $format , array $args ) : int
printf() but accepts an array of arguments,
rather than a variable number of
arguments.
sprintf Return a formatted string sprintf ( string $format [, mixed $... ] ) : string
vsprintf Return a formatted string. Operates as vsprintf ( string $format , array $args ) : string
sprintf() but accepts an array of arguments,
rather than a variable number of
arguments.
wordwrap Wraps a string to a given number of wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut
characters = FALSE ]]] ) : string
preg_match Perform a regular expression match preg_match ( string $pattern , string $subject [, array &$matches [, int
$flags = 0 [, int $offset = 0 ]]] ) : int
preg_match_all Perform a global regular expression match preg_match_all ( string $pattern , string $subject [, array &$matches [,
9
int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] ) : int
10