vadnica-logo
Editor My Blog My Services About the Project Telegram O meni O meni

PHP Strings

A string is a sequence of characters enclosed in either double (") or single (') quotes in PHP. It is crucial that you do not start a string with one type of quote and end it with another. The main difference between them is that double quotes allow for the direct insertion of variables (e.g., "$name") and special escape characters (e.g., \n for a new line), whereas single quotes treat everything as raw plain text.

EXAMPLE
RESULT
The result will be displayed here...

Overview of the Most Common String Functions

For faster and easier text management, PHP provides a rich collection of built-in functions. The list below shows the essential string tools that you will use most frequently:

  1. eval(): Evaluates and executes the string content as PHP code.
    Warning: This function is dangerous if unverified user data is passed into it!
  2. strlen(): Returns the length of a string (number of characters).
  3. str_word_count(): Counts the number of words in a string.
  4. strpos(): Finds the position of the first occurrence of a specific substring.
  5. strtoupper() / strtolower(): Converts a string to uppercase or lowercase.
  6. str_replace(): Replaces some characters or words with other characters or words in a string.
  7. strrev(): Reverses a string.
  8. trim(): Removes whitespace or other predefined characters from both sides of a string.
  9. explode(): Splits a string into an array based on a delimiter.
  10. substr(): Returns a specific part (substring) of a string.
  11. escape characters (\): Allow you to insert quotes, tabs, and other special characters into strings.

PHP Strings Quick Overview

An overview of built-in PHP functions for working with strings. You can copy and paste the examples below directly into your editor for testing:

Found: -
Name Description Example (Code for testing)
addcslashes() Returns a string with backslashes before specified characters (C-style). echo addcslashes("Borut", "A..Z");
addslashes() Returns a string with backslashes before characters that need to be escaped (e.g., quotes). echo addslashes("O'Reilly");
bin2hex() Converts a string of binary data into hexadecimal representation. echo bin2hex("PHP");
chop() Alias of rtrim() - removes whitespace or other characters from the right side of a string. echo chop("Test ");
chr() Returns a specific character from the given ASCII value. echo chr(65);
chunk_split() Splits a string into smaller chunks of a specified length (useful for base64 transfers). echo chunk_split("ABCDEF", 2, "-");
convert_uudecode() Decodes a uuencoded string. echo convert_uudecode("#44HP``\n");
convert_uuencode() Uuencodes a string. echo convert_uuencode("Test");
count_chars() Returns statistics about character usage in a string. print_r(count_chars("Borut", 1));
crc32() Calculates the 32-bit cyclic redundancy check polynomial (CRC) for a string. echo crc32("Tutorial");
crypt() One-way string hashing. echo crypt("password123", "salt");
echo() Outputs one or more strings directly to the output. echo "Hello", " world";
explode() Splits a string into an array by a specified delimiter. print_r(explode(",", "a,b,c"));
fprintf() Writes a formatted string directly to an open file stream. $f = fopen("t.txt", "w"); fprintf($f, "%d", 10);
get_html_translation_table() Returns the translation table used by htmlentities() and htmlspecialchars(). print_r(get_html_translation_table(HTML_SPECIALCHARS));
hex2bin() Decodes a hexadecimally encoded string back into binary format. echo hex2bin("504850");
html_entity_decode() Converts HTML entities (e.g., &lt;) back to their corresponding characters (<). ▶ View Code
htmlentities() Converts all applicable characters to HTML entities. ▶ View Code
htmlspecialchars() Converts special characters (like <, >, &) to HTML entities. ▶ View Code
htmlspecialchars_decode() Converts special HTML entities back to characters. ▶ View Code
implode() Joins array elements into a single string using a delimiter (same as join). echo implode("-", [1, 2, 3]);
join() Alias of implode() - joins array elements into a string. echo join(" ", ["Borut", "codes"]);
lcfirst() Converts the first character of a string to lowercase. echo lcfirst("PHP");
levenshtein() Calculates the Levenshtein distance between two strings. echo levenshtein("cat", "bat");
localeconv() Returns numeric and monetary formatting information based on current locale settings. print_r(localeconv());
ltrim() Removes whitespace or other characters from the left side of a string. echo ltrim(" string");
md5() Calculates the MD5 hash of a string. echo md5("test");
md5_file() Calculates the MD5 hash of a given file. echo md5_file("index.php");
metaphone() Calculates the metaphone key of a string (how a word sounds in English). echo metaphone("programming");
nl2br() Inserts HTML line breaks (<br />) before all newlines in a string. echo nl2br("First\nSecond");
number_format() Formats a number with grouped thousands and a custom number of decimals. echo number_format(1500.75, 2, ".", ",");
ord() Returns the numeric ASCII value of the first character of a string. echo ord("A");
parse_str() Parses a URL query string into variables. parse_str("name=Borut", $output); print_r($output);
print() Outputs a string (similar to echo, but always returns 1). print("Text");
printf() Outputs a formatted string according to specified placeholders (%s, %d, etc.). printf("Age: %d", 52);
preg_replace() Searches for patterns and replaces them with a new string. echo preg_replace("/\d+/", "X", "Code123");
preg_match() Checks if a pattern appears in a string (returns 0 or 1). echo preg_match("/php/i", "PHP code");
preg_match_all() Finds all pattern matches in a string and saves them into an array. preg_match_all("/\d/", "1a2b3c", $m); print_r($m);
preg_split() Splits a string into an array based on a regular expression pattern. print_r(preg_split("/[\s,]+/", "a, b c"));
preg_grep() Returns array elements that match a specific regular expression pattern. print_r(preg_grep("/^p/", ["php", "html", "python"]));
preg_quote() Quotes regular expression special characters by adding a backslash. echo preg_quote("usd$");
quoted_printable_decode() Decodes a quoted-printable string into an 8-bit string. echo quoted_printable_decode("Borut=3DA");
quoted_printable_encode() Converts an 8-bit string into a quoted-printable string. echo quoted_printable_encode("Borut=");
quotemeta() Quotes special characters by adding a backslash (characters like . \ + * [ ^ ] ( $ )). echo quotemeta("Hello. How are you?");
rtrim() Removes whitespace or other characters from the right side of a string. echo rtrim("string ");
setlocale() Sets locale information (language, currency, time). echo setlocale(LC_ALL, "en_US.utf8");
sha1() Calculates the SHA-1 hash of a string. echo sha1("code");
sha1_file() Calculates the SHA-1 hash of a file. echo sha1_file("index.php");
similar_text() Calculates the similarity between two strings in percentage. echo similar_text("Borut", "Gorut", $p); echo " ($p%)";
soundex() Calculates the soundex key of a string (phonetic searching for last names). echo soundex("Smith");
sprintf() Returns a formatted string (instead of printing it directly). $s = sprintf("Price: %d$", 10); echo $s;
sscanf() Parses input from a string according to a specified format. sscanf("ID: 456", "ID: %d", $id); echo $id;
str_contains() Checks if a string contains a specific substring (New in PHP 8.0). var_dump(str_contains("PHP Tutorial", "PHP"));
str_ends_with() Checks if a string ends with a specific substring (New in PHP 8.0). var_dump(str_ends_with("image.png", ".png"));
str_getcsv() Parses a CSV string into an array. print_r(str_getcsv("Borut,52,Slovenia", ",", '"', "\\"));
str_ireplace() Replaces substrings (case-insensitive). echo str_ireplace("php", "JS", "Learning PHP");
str_pad() Pads a string to a certain length with another string. echo str_pad("1", 3, "0", STR_PAD_LEFT);
str_repeat() Repeats a string a specified number of times. echo str_repeat("X", 5);
str_replace() Replaces all occurrences of the search substring with the replacement string. echo str_replace("red", "blue", "red car");
str_rot13() Performs the ROT13 transform on a string. echo str_rot13("PHP");
str_shuffle() Randomly shuffles all characters in a string. echo str_shuffle("Borut");
str_split() Converts a string to an array where each element is of a specified length. print_r(str_split("CODE", 2));
str_starts_with() Checks if a string starts with a specific substring (New in PHP 8.0). var_dump(str_starts_with("https://v", "https"));
str_word_count() Counts the number of words in a string. echo str_word_count("PHP is awesome");
strcasecmp() Binary safe case-insensitive string comparison. echo strcasecmp("Test", "test");
strchr() Alias of strstr() - finds the first occurrence of a character. echo strchr("user@mail.com", "@");
strcmp() Binary safe case-sensitive string comparison. echo strcmp("Test", "Test");
strcoll() Locale based string comparison. echo strcoll("a", "b");
strcspn() Finds the length of the initial segment of a string which does NOT contain any specified characters. echo strcspn("Borut123", "0123456789");
strip_tags() Strips HTML and PHP tags from a string. echo strip_tags("Bold");
stripcslashes() Un-escapes a string escaped with addcslashes(). echo stripcslashes("B\orut");
stripslashes() Un-escapes a string escaped with addslashes(). echo stripslashes("O'Reilly");
stripos() Finds the position of the first occurrence of a case-insensitive substring. echo stripos("Car", "a");
stristr() Case-insensitive strstr(). Returns part of the string from the first occurrence onwards. echo stristr("Test@Domain", "d");
strlen() Returns the total number of characters (length) of a string. echo strlen("Code");
strnatcasecmp() Case-insensitive string comparison using a "natural order" algorithm. echo strnatcasecmp("img10.png", "img2.png");
strnatcmp() Case-sensitive string comparison using a "natural order" algorithm. echo strnatcmp("10", "2");
strncasecmp() Binary safe case-insensitive string comparison of the first N characters. echo strncasecmp("Borut", "BOR", 3);
strncmp() Binary safe case-sensitive string comparison of the first N characters. echo strncmp("Code1", "Code2", 4);
strpbrk() Searches a string for any character from a given set. echo strpbrk("Borut", "ut");
strpos() Finds the position of the first occurrence of a case-sensitive substring. echo strpos("Program", "g");
strrchr() Finds the last occurrence of a character in a string and returns the rest. echo strrchr("path/to/file.txt", "/");
strrev() Reverses a string (last character becomes first). echo strrev("ABC");
strripos() Finds the position of the last occurrence of a case-insensitive substring. echo strripos("abcABC", "a");
strrpos() Finds the position of the last occurrence of a case-sensitive substring. echo strrpos("abcABC", "a");
strspn() Finds the length of the initial segment of a string which consists ENTIRELY of characters from a given mask. echo strspn("123abc", "0123456789");
strstr() Case-sensitive search. Returns part of the string from the first occurrence onwards. echo strstr("name@domain.com", "@");
strtok() Tokenizes a string into smaller fragments based on split characters. $t = strtok("a b", " "); echo $t;
strtolower() Converts a string to lowercase. echo strtolower("LOWER");
strtoupper() Converts a string to uppercase. echo strtoupper("upper");
strtr() Translates characters or replaces substrings in a string. echo strtr("hallo", "a", "e");
substr() Returns a specified part (substring) from a larger string. echo substr("Slovenia", 0, 3);
substr_compare() Binary safe comparison of two strings from an offset, up to N characters. echo substr_compare("abc", "bc", 1, 2);
substr_count() Counts the number of substring occurrences inside a string. echo substr_count("banana", "an");
substr_replace() Replaces text within a portion of a string at a specified position. echo substr_replace("Code", "X", 0, 1);
trim() Strips whitespace and other characters from the beginning and end of a string. echo trim(" string ");
ucfirst() Converts the first character of the entire string to uppercase. echo ucfirst("text");
ucwords() Converts the first character of each word in a string to uppercase. echo ucwords("hello world");
vfprintf() Writes a formatted string (with arguments in an array) to a file stream. $f = fopen("t.txt", "w"); vfprintf($f, "%s", ["OK"]);
vprintf() Outputs a formatted string using an array of arguments. vprintf("Age: %d", [52]);
vsprintf() Returns a formatted string using an array of arguments. $s = vsprintf("%s %s", ["A", "B"]); echo $s;
wordwrap() Wraps a string to a given number of characters using a break character. echo wordwrap("Very long text", 5);

Curious about the background? Octal and Hexadecimal Codes in Strings

While working with strings, you will occasionally encounter representations like \120 (octal) or \x50 (hexadecimal). Computers don't understand letters natively—they only understand numbers. These notations allow programmers to inject special commands, hidden symbols, or characters from the standard ASCII table directly into text without having to type the actual characters.

💡 When is this useful?
Although you won't write these codes often in everyday PHP, they are crucial when sending raw sensor data from an Arduino or other microcontrollers to a webpage, managing permissions on Linux servers (e.g., chmod 755), or handling advanced security and encryption challenges.
Hexadecimal notation Allows inserting characters into a string using hexadecimal codes (e.g., \x50 for the letter P). ▶ View Code
Octal notation Allows inserting characters into a string using octal codes (e.g., \120 for the letter P). ▶ View Code