String Functions – Searching and Replacing
| Function | Purpose |
|---|
| strpos(haystack, needle [, offset]) | Position of the first occurrence (case-sensitive), or false. |
| stripos(...) | Like strpos(), case-insensitive. |
| strrpos(...) / strripos(...) | Position of the last occurrence (case-sensitive / insensitive). |
| strstr(haystack, needle) | Returns the part of haystack from the first occurrence of needle. strchr() is an alias. |
| stristr(haystack, needle) | Case-insensitive strstr(). |
| strrchr(haystack, char) | Returns the part from the last occurrence of a character. |
| str_contains / str_starts_with / str_ends_with (haystack, needle) | Checks whether a string contains / starts with / ends with another (PHP 8). |
| substr(string, start [, length]) | Returns part of a string. |
| substr_count(haystack, needle) | Counts occurrences of a substring. |
| substr_replace(string, replacement, start [, length]) | Replaces part of a string. |
| substr_compare(a, b, offset [, length, case_insensitive]) | Compares two strings from an offset. |
| str_replace(search, replace, subject [, &count]) | Replaces all occurrences (case-sensitive). |
| str_ireplace(...) | Case-insensitive str_replace(). |
| strtr(string, from, to) or strtr(string, array) | Translates characters or replaces substrings. |
| strpbrk(string, char_list) | Searches a string for any of a set of characters. |
| strspn(string, mask) / strcspn(string, mask) | Length of the initial part that consists of / does not contain the mask characters. |
| strtok(string, token) | Splits a string into tokens, one call at a time. |
File: htdocs/phpbook/ch29/search.php
<?php
$s = "PHP is fun. Learning PHP with XAMPP is easy.";
echo "strlen: " . strlen($s) . ", str_word_count: " . str_word_count($s) . "<br>";
echo "strpos('PHP'): " . strpos($s, "PHP") . ", strrpos('PHP'): " . strrpos($s, "PHP") . "<br>";
echo "stripos('php'): " . stripos($s, "php") . "<br>";
echo "substr_count('PHP'): " . substr_count($s, "PHP") . "<br>";
echo "strstr('Learning'): " . strstr($s, "Learning") . "<br>";
echo "strrchr(' '): '" . strrchr($s, " ") . "'<br>";
echo "substr(-5): " . substr($s, -5) . "<br>";
echo "str_replace: " . str_replace("PHP", "Python", $s, $count) . " ($count replacements)<br>";
echo "str_ireplace('xampp','WAMP'): " . str_ireplace("xampp", "WAMP", $s) . "<br>";
echo "substr_replace: " . substr_replace("Hello World", "PHP", 6, 5) . "<br>";
echo "strtr: " . strtr("Hi all, I said hello", ["Hi" => "Hello", "hello" => "hi"]) . "<br>";
echo "str_starts_with('PHP'): " . var_export(str_starts_with($s, "PHP"), true) . "<br>";
echo "strtok: ";
$tok = strtok("red,green;blue", ",;");
while ($tok !== false) { echo "[$tok] "; $tok = strtok(",;"); }
?>
OUTPUT browser · http://localhost/phpbook/ch29/search.php
strlen: 44, str_word_count: 9
strpos('PHP'): 0, strrpos('PHP'): 21
stripos('php'): 0
substr_count('PHP'): 2
strstr('Learning'): Learning PHP with XAMPP is easy.
strrchr(' '): ' easy.'
substr(-5): easy.
str_replace: Python is fun. Learning Python with XAMPP is easy. (2 replacements)
str_ireplace('xampp','WAMP'): PHP is fun. Learning PHP with WAMP is easy.
substr_replace: Hello PHP
strtr: Hello all, I said hi
str_starts_with('PHP'): true
strtok: [red] [green] [blue]
String Functions – Splitting, Joining and Formatting
| Function | Purpose |
|---|
| explode(separator, string [, limit]) | Splits a string by a separator into an array. Opposite of implode(). |
| implode(glue, array) | Joins array elements into a string. join() is an alias. |
| str_split(string [, length]) | Splits a string into an array of chunks. |
| str_getcsv(string [, separator]) | Parses a CSV line into an array. |
| printf(format, args...) | Outputs a formatted string. |
| sprintf(format, args...) | Returns a formatted string. |
| vprintf / vsprintf / vfprintf (format, args_array) | Like printf/sprintf/fprintf but with an array of arguments. |
| fprintf(stream, format, args...) | Writes a formatted string to a stream (file). |
| sscanf(string, format, &vars...) | Parses input from a string according to a format. |
| number_format(number [, decimals, dec_point, thousands]) | Formats a number with grouped thousands. |
| parse_str(string, &result) | Parses a query string into an array. |
File: htdocs/phpbook/ch29/format.php
<?php
$csv = "Asha,Bhopal,82";
$parts = explode(",", $csv);
echo "explode: " . $parts[0] . " | " . $parts[1] . " | " . $parts[2] . "<br>";
echo "implode: " . implode(" - ", ["PHP", "MySQLi", "AJAX"]) . "<br>";
echo "str_split: " . implode(" ", str_split("ABCDEFGH", 3)) . "<br>";
printf("printf: %s scored %d marks (%.1f%%)<br>", "Ravi", 456, 456 / 5);
$s = sprintf("%05d | %-8s| %8.2f | %x | %b", 42, "left", 3.14159, 255, 5);
echo "sprintf: " . str_replace(" ", " ", $s) . "<br>";
echo "vsprintf: " . vsprintf("%s is %d years old", ["Neha", 23]) . "<br>";
sscanf("Roll: 105 Name: Kiran", "Roll: %d Name: %s", $roll, $name);
echo "sscanf: roll=$roll, name=$name<br>";
parse_str("city=Bhopal&pin=462011", $q);
echo "parse_str: " . json_encode($q) . "<br>";
echo "wordwrap: " . wordwrap("The quick brown fox jumps over the lazy dog", 15, "<br>", true);
?>
OUTPUT browser · http://localhost/phpbook/ch29/format.php
explode: Asha | Bhopal | 82
implode: PHP - MySQLi - AJAX
str_split: ABC DEF GH
printf: Ravi scored 456 marks (91.2%)
sprintf: 00042 | left | 3.14 | ff | 101
vsprintf: Neha is 23 years old
sscanf: roll=105, name=Kiran
parse_str: {"city":"Bhopal","pin":"462011"}
wordwrap: The quick brown
fox jumps over
the lazy dog
String Functions – Comparing
| Function | Purpose |
|---|
| strcmp(a, b) | Compares two strings (case-sensitive); returns < 0, 0 or > 0. |
| strcasecmp(a, b) | Case-insensitive comparison. |
| strncmp(a, b, n) / strncasecmp(a, b, n) | Compares the first n characters (case-sensitive / insensitive). |
| strnatcmp(a, b) / strnatcasecmp(a, b) | "Natural order" comparison (case-sensitive / insensitive). |
| strcoll(a, b) | Locale-based comparison. |
| similar_text(a, b [, &percent]) | Calculates the similarity of two strings. |
| levenshtein(a, b) | Number of single-character edits between two strings. |
| soundex(string) / metaphone(string) | Phonetic keys – words that sound alike get the same key. |
File: htdocs/phpbook/ch29/compare.php
<?php
echo "strcmp('apple','Apple'): " . strcmp("apple", "Apple") . "<br>";
echo "strcasecmp('apple','Apple'): " . strcasecmp("apple", "Apple") . "<br>";
echo "strncmp('PHP8','PHP7',3): " . strncmp("PHP8", "PHP7", 3) . "<br>";
echo "strcmp vs strnatcmp ('img2','img10'): " . strcmp("img2", "img10") . " / " . strnatcmp("img2", "img10") . "<br>";
similar_text("World", "Word", $pct);
echo "similar_text('World','Word'): " . round($pct, 1) . "%<br>";
echo "levenshtein('kitten','sitting'): " . levenshtein("kitten", "sitting") . "<br>";
echo "soundex: Robert=" . soundex("Robert") . ", Rupert=" . soundex("Rupert") . "<br>";
echo "metaphone('Thompson'): " . metaphone("Thompson");
?>
OUTPUT browser · http://localhost/phpbook/ch29/compare.php
strcmp('apple','Apple'): 32
strcasecmp('apple','Apple'): 0
strncmp('PHP8','PHP7',3): 0
strcmp vs strnatcmp ('img2','img10'): 1 / -1
similar_text('World','Word'): 88.9%
levenshtein('kitten','sitting'): 3
soundex: Robert=R163, Rupert=R163
metaphone('Thompson'): 0MPSN
String Functions – HTML, Encoding and Hashing
| Function | Purpose |
|---|
| htmlspecialchars(string [, flags]) | Converts & " ' < > into HTML entities. |
| htmlentities(string [, flags]) | Converts all applicable characters into HTML entities. |
| html_entity_decode(string) / htmlspecialchars_decode(string) | Converts entities back to characters. |
| get_html_translation_table([table]) | Returns the translation table used by the two functions above. |
| strip_tags(string [, allowed]) | Removes HTML and PHP tags. |
| addslashes(string) / stripslashes(string) | Adds / removes backslashes before quotes and backslashes. |
| addcslashes(string, chars) / stripcslashes(string) | C-style escaping of given characters / un-escaping. |
| quotemeta(string) | Escapes the meta characters . \ + * ? [ ^ ] $ ( ). |
| chr(code) / ord(char) | Character of an ASCII code / ASCII code of the first character. |
| bin2hex(string) / hex2bin(string) | Converts binary data to hexadecimal and back. |
| base64_encode / base64_decode | Base64 encoding and decoding. |
| urlencode / urldecode / rawurlencode | URL encoding and decoding. |
| str_rot13(string) | ROT13 encoding. |
| convert_uuencode / convert_uudecode | uuencode encoding and decoding. |
| quoted_printable_decode / quoted_printable_encode | Quoted-printable decoding and encoding. |
| md5(string) / md5_file(file) | MD5 hash (32 hex characters) – not for passwords. |
| sha1(string) / sha1_file(file) | SHA-1 hash (40 hex characters) – not for passwords. |
| crc32(string) | 32-bit CRC checksum. |
| hash(algorithm, data) | Hash with any algorithm, e.g. sha256. |
| crypt(string, salt) | One-way hashing (PHP 8: the salt is required). |
| password_hash(password, algo) / password_verify(password, hash) | The correct way to store and check passwords. |
File: htdocs/phpbook/ch29/encode.php
<?php
$html = "<b>Tom & Jerry's</b> \"show\"";
echo "htmlspecialchars: " . htmlspecialchars(htmlspecialchars($html)) . "<br>";
echo "strip_tags: " . strip_tags($html) . "<br>";
echo "addslashes: " . addslashes("It's \"PHP\"") . "<br>";
echo "chr(65) = " . chr(65) . ", ord('a') = " . ord("a") . "<br>";
echo "bin2hex('PHP'): " . bin2hex("PHP") . "<br>";
echo "base64_encode('PHP 8'): " . base64_encode("PHP 8") . " → " . base64_decode("UEhQIDg=") . "<br>";
echo "urlencode('a b&c=d'): " . urlencode("a b&c=d") . "<br>";
echo "str_rot13('Hello'): " . str_rot13("Hello") . "<br>";
echo "md5('php'): " . md5("php") . "<br>";
echo "sha1('php'): " . sha1("php") . "<br>";
echo "hash('sha256','php'): " . substr(hash("sha256", "php"), 0, 32) . "…<br>";
echo "crc32('php'): " . crc32("php") . "<br>";
$h = password_hash("Secret@123", PASSWORD_DEFAULT);
echo "password_hash length: " . strlen($h) . ", starts with " . substr($h, 0, 4) . "<br>";
echo "password_verify: " . var_export(password_verify("Secret@123", $h), true);
?>
OUTPUT browser · http://localhost/phpbook/ch29/encode.php
htmlspecialchars: <b>Tom & Jerry's</b> "show"
strip_tags: Tom & Jerry's "show"
addslashes: It\'s \"PHP\"
chr(65) = A, ord('a') = 97
bin2hex('PHP'): 504850
base64_encode('PHP 8'): UEhQIDg= → PHP 8
urlencode('a b&c=d'): a+b%26c%3Dd
str_rot13('Hello'): Uryyb
md5('php'): e1bfd762321e409cee4ac0b6e841963c
sha1('php'): 47425e4490d1548713efea3b8a6f5d778e4b1766
hash('sha256','php'): 12a5d18ee896e59954bdce0f4acc7212…
crc32('php'): 1452351953
password_hash length: 60, starts with $2y$
password_verify: true
Never store passwords with md5() or sha1() – they are fast and can be cracked. Use password_hash() and password_verify() (Chapter 36 and the project use them).
String functions removed from PHP
| Function | Removed in | Use instead |
|---|
| ereg(), eregi() | PHP 7.0 | preg_match() with the i flag |
| ereg_replace(), eregi_replace() | PHP 7.0 | preg_replace() |
| split(), spliti() | PHP 7.0 | preg_split() or explode() |
| sql_regcase() | PHP 7.0 | preg_match() with the i flag |
| money_format() | PHP 8.0 | number_format() or NumberFormatter |
| convert_cyr_string() | PHP 8.0 | mb_convert_encoding() or iconv() |
| hebrevc() | PHP 8.0 | nl2br(hebrev($text)) |
| fgetss() | PHP 8.0 | strip_tags(fgets($h)) |
| utf8_encode(), utf8_decode() | deprecated 8.2 | mb_convert_encoding() |
Variable Functions
| Function | Purpose |
|---|
| isset(var, ...) | Checks whether a variable is set and not null. |
| empty(var) | Checks whether a variable is empty ("", 0, "0", null, false, []) or not set. |
| unset(var, ...) | Destroys the variable. |
| is_null(var) | Checks whether a variable is null. |
| gettype(var) / get_debug_type(var) | Returns the type of a variable (get_debug_type(): PHP 8 names such as int). |
| settype(&var, type) | Sets the type of a variable. |
| intval(var [, base]) | Integer value of a variable (optionally from another base). |
| floatval(var) | Float value. doubleval() is an alias. |
| strval(var) / boolval(var) | String / boolean value of a variable. |
| is_int / is_integer / is_long (var) | Checks whether a variable is an integer. |
| is_float / is_double (var) | Checks whether a variable is a float. |
| is_string / is_bool / is_array / is_object / is_resource / is_iterable / is_countable (var) | Type checks. |
| is_numeric(var) | Checks whether a variable is a number or a numeric string. |
| is_scalar(var) | Checks whether it is int, float, string or bool. |
| is_callable(var) | Checks whether it can be called as a function. |
| print_r(var [, return]) | Prints human-readable information about a variable. |
| var_dump(var, ...) | Dumps type and value information. |
| var_export(var [, return]) | Outputs or returns valid PHP code representing the variable. |
| serialize(value) / unserialize(string) | Converts a value to a storable string and back. |
| get_defined_vars() | Returns all defined variables of the current scope. |
| get_resource_type(handle) | Returns the type of a resource. |
| is_real(var) | Removed in PHP 8.0 – use is_float(). |
| import_request_variables(types [, prefix]) | Removed in PHP 5.4 – read $_GET/$_POST. |
File: htdocs/phpbook/ch29/variables.php
<?php
$values = [42, 3.5, "123", "12abc", "", null, true, [1, 2]];
foreach ($values as $v) {
echo str_pad(var_export($v, true), 18) . " type=" . get_debug_type($v)
. " numeric=" . var_export(is_numeric($v), true)
. " empty=" . var_export(empty($v), true) . "<br>";
}
$x = "25.7 kg";
echo "intval: " . intval($x) . ", floatval: " . floatval($x) . ", intval('ff', 16): " . intval("ff", 16) . "<br>";
settype($x, "integer");
echo "after settype(integer): "; var_dump($x);
$data = ["name" => "Asha", "marks" => [82, 75]];
$ser = serialize($data);
echo "<br>serialize: $ser<br>";
echo "unserialize name: " . unserialize($ser)["name"] . "<br>";
echo "var_export: " . var_export(["a" => 1, "b" => true], true);
?>
OUTPUT browser · http://localhost/phpbook/ch29/variables.php
42 type=int numeric=true empty=false
3.5 type=float numeric=true empty=false
'123' type=string numeric=true empty=false
'12abc' type=string numeric=false empty=false
'' type=string numeric=false empty=true
NULL type=null numeric=false empty=true
true type=bool numeric=false empty=false
array ( 0 => 1, 1 => 2, ) type=array numeric=false empty=false
intval: 25, floatval: 25.7, intval('ff', 16): 255
after settype(integer): int(25)
serialize: a:2:{s:4:"name";s:4:"Asha";s:5:"marks";a:2:{i:0;i:82;i:1;i:75;}}
unserialize name: Asha
var_export: array ( 'a' => 1, 'b' => true, )
Miscellaneous Functions
| Function | Purpose |
|---|
| define(name, value) / defined(name) / constant(name) | Defines a constant / checks it exists / returns its value (also with a dynamic name). |
| die(message) / exit([status]) | Outputs a message and ends the script. |
| eval(code) | Evaluates a string as PHP code – dangerous with user input. |
| sleep(seconds) / usleep(microseconds) / time_nanosleep(s, ns) | Delays execution. |
| uniqid([prefix, more_entropy]) | Generates a unique id based on the current time in microseconds. |
| highlight_string(code [, return]) | Syntax-highlights a string of PHP code. |
| highlight_file(file [, return]) | Syntax-highlights a file. show_source() is an alias. |
| php_strip_whitespace(file) | Returns the source of a file without comments and white space. |
| pack(format, values...) / unpack(format, data) | Packs data into a binary string / unpacks it. |
| connection_aborted() / connection_status() | Checks whether the client disconnected / the connection status. |
| ignore_user_abort([enable]) | Lets a script continue if the user aborts the connection. |
| get_browser([user_agent]) | Information about the browser's capabilities (needs a browscap file configured in php.ini). |
| php_check_syntax(file) | Removed in PHP 5.0.5 – run php -l file.php in the XAMPP Shell. |
| connection_timeout() | Removed long ago – use connection_status(). |
File: htdocs/phpbook/ch29/misc.php
<?php
define("COURSE", "PHP Basics to Advance");
$name = "COURSE";
echo "constant('$name'): " . constant($name) . ", defined: " . var_export(defined("COURSE"), true) . "<br>";
$id1 = uniqid(); $id2 = uniqid("INV-");
echo "uniqid lengths: " . strlen($id1) . " and " . strlen($id2) . " (prefix " . substr($id2, 0, 4) . ")<br>";
$start = microtime(true);
usleep(200000); // 0.2 seconds
echo "usleep(200000) took about " . round(microtime(true) - $start, 1) . " s<br>";
$bin = pack("nvN", 258, 258, 1);
echo "pack('nvN') length: " . strlen($bin) . " bytes, hex: " . bin2hex($bin) . "<br>";
print_r(unpack("nbig/vlittle/Nlong", $bin));
echo "<br>connection_status(): " . connection_status() . " (0 = normal)<br>";
echo "highlight_string:<br>";
highlight_string('<?php echo "Hello"; // greet ?>');
?>
OUTPUT browser · http://localhost/phpbook/ch29/misc.php
constant('COURSE'): PHP Basics to Advance, defined: true
uniqid lengths: 13 and 17 (prefix INV-)
usleep(200000) took about 0.2 s
pack('nvN') length: 8 bytes, hex: 0102020100000001
Array ( [big] => 258 [little] => 258 [long] => 1 )
connection_status(): 0 (0 = normal)
highlight_string:
<?php echo "Hello"; // greet ?>