39 PHP String Functions You Can’t Live Without
In this article, we’ll take a quick look at the most popular PHP string functions and provide simple examples. Enjoy!
addslashes()
The PHP addslashes()
function adds a backslash character (\) before certain characters in a string to make the string safe to store in a database or display on a web page.
The characters that are preceded by a backslash are single quote (‘), double quote (“), backslash (), and NUL (the NULL byte).
addslashes() example
$string = "This is John's book";
$safe_string = addslashes($string);
echo $safe_string;
The above code will output This is John\'s book
.
As you can see, the apostrophe (‘) in the original string is now preceded by a backslash (\).
chr()
The PHP string function chr()
returns a string containing a character corresponding to the ASCII code passed as its parameter. The ASCII code should be an integer between 0 and 255.
Syntax: string chr ( int $ascii )
chr() example
$num = 65; $char = chr($num); echo $char;
Output: A
chunk_split()
The chunk_split()
function is used to split a string into smaller chunks of a specific length. It can be useful when working with data that needs to be transmitted in smaller pieces or when formatting data to make it more readable.
The function takes three parameters: the string to be split, the length of each chunk, and the separator string that is inserted between each chunk. The separator string is optional, with a default of '\r\n'
.
chunk_split() example
Split a string into chunks of length 3 with a separator of '-'
:
$original_string = 'Hello world';
$chunked_string = chunk_split($original_string, 3, '-');
echo $chunked_string;
Output: Hel-lo -wor-ld
convert_cyr_string()
The convert_cyr_string()
function is a string function in PHP that is used to convert a string from one Cyrillic character set to another. This function only works with Cyrillic character sets.
Syntax: convert_cyr_string(string $str, string $from, string $to): string
Parameter Values:
str
: Required. Specifies the string to be convertedfrom
: Required. Specifies the source Cyrillic character setto
: Required. Specifies the destination Cyrillic character set
This function returns the converted string.
convert_cyr_string() example
$str = "Ñèíèé";
$strConverted = convert_cyr_string($str, "k", "w");
echo $strConverted; // Output: "Привет"
In this example, the string Ñèíèé
is converted from the k
character set to the w
character set using the convert_cyr_string()
function, which results in the string Привет
.
convert_uudecode()
The PHP string function convert_uudecode()
decodes a uuencoded string. Uuencode is a binary-to-text encoding method that was used to send binary data over text-only transmission channels.
Syntax: string convert_uudecode ( string $data )
Parameter Values: the parameter “data” is the uuencoded data that needs to be decoded.
convert_uudecode() example
Here’s an example code snippet that demonstrates the usage of the convert_uudecode()
function:
$encoded_string = "Mi9vdApyb290ClNvbWUgdGVzdCBzdHJpbmcK";
$decoded_string = convert_uudecode($encoded_string);
echo $decoded_string;
In the above code, the encoded string Mi9vdApyb290ClNvbWUgdGVzdCBzdHJpbmcK
is decoded using the convert_uudecode()
function and the decoded string is printed using the echo statement.
convert_uuencode()
The PHP string function convert_uuencode()
encodes a string using the uuencode algorithm. This algorithm is used to transfer binary data over text-only transmissions such as email or newsgroups.
The encoded output is a string that contains only printable ASCII characters, making it suitable for text transmission. The function takes a single parameter, the string to be encoded, and returns the encoded output.
convert_uuencode() example
$string = "Hello, world!";
$encoded = convert_uuencode($string);
echo $encoded;
The output of this code would be: M/&5L;&\@=V]R\:6YT:&5R(&EF("@B
Note that this encoded string can be safely transmitted over text-only channels without fear of data loss or corruption.
count_chars()
The PHP count_chars()
function returns information about the characters used in a string. There are two modes of operation for this function: it can either return a string containing all the different characters used or an associative array with the frequency of each character in the string. This function is useful for analyzing and manipulating textual data.
Syntax: count_chars(string,mode)
Parameters:
string
: Required. Specifies the string to be analyzedmode
: Optional. Specifies the return type. Default is 0. Accepts 0, 1, 2, 3 and 4 values. 0 returns string with all unique characters, 1 returns array with count of each character, 2 returns array with character frequency, 3 returns array with only characters used, 4 returns array with only characters not used.
Return Value:
- When mode is 0, function returns only unique characters used in the specified string.
- When mode is 1, function returns an array with the ASCII value of each character used as an index, and the count of the character appearing in the string as a value.
- When mode is 2, function returns an array with the ASCII value of each character used as an index, and the frequency of the character appearing in the string as a value.
- When mode is 3, function returns an array with the ASCII value of each character used as an index, but only includes characters used in the string.
- When mode is 4, function returns an array with the ASCII value of each character not used as an index, but only includes characters not used in the string.
count_chars() example
$string = "Hello, World!";
$uniqueCharacters = count_chars($string, 0);
$countCharacters = count_chars($string, 1);
$charFrequency = count_chars($string, 2);`
echo "Unique characters: ".$uniqueCharacters."
";
echo "Count characters:
";
print_r($countCharacters);
echo "
";
echo "Character frequency:
";
print_r($charFrequency);
Output:
Unique characters: ! $ , . H W d e l o r
Count characters:
Array ( [32] => 1 [33] => 1 [36] => 1 [44] => 1 [46] => 1 [72] => 1 [87] => 1 [100] => 1 [101] => 1 [108] => 3 [111] => 2 [114] => 1 [115] => 1 )
Character frequency:
Array ( [32] => 1 [33] => 1 [36] => 1 [44] => 1 [46] => 1 [72] => 1 [87] => 1 [100] => 1 [101] => 1 [108] => 3 [111] => 2 [114] => 1 [115] => 1 )
crc32()
The crc32()
function in PHP is used to calculate the 32-bit cyclic redundancy checksum of a given string. It is particularly useful in data verification and error detection process. The returned value is a positive integer representation of the checksum, which can be used for comparison purposes to detect data changes.
crc32() example
$string = "Hello World!";
$crc = crc32($string);
echo $crc;
crypt()
The PHP string function crypt()
is used to generate a hashed password. It uses a one-way encryption algorithm to secure passwords. The function takes two parameters: the string to be encrypted and the salt to be used for encryption.
The salt is a random string that is added to the password before hashing. This adds an extra layer of security to the password, making it harder to crack. The resulting hash can be stored in a database for later verification.
crypt() example
$password = "mypassword";
$salt = "XY";
$encrypted_password = crypt($password, $salt);
echo $encrypted_password;
This will output a hashed password that can be stored in a database. The salt can be different for each user and can be stored along with the hashed password in the database.
echo()
The echo()
function is used in PHP to output one or more strings to the browser or to a file. It is commonly used to display text and HTML code on a webpage, to print variables and values, and to debug code by displaying messages.
The echo()
function can be used with or without parentheses, but it is recommended to use them for clarity and consistency. It can output multiple strings separated by commas, concatenation, or concatenation assignment.
echo() example
// Output a single string
echo "Hello, world!";
// Output multiple strings separated by commas
echo "My name is", "John","Doe";
// Output a variable value
$name = "Jane";
echo "My name is $name.";
explode()
The explode()
function in PHP is used to split a string into an array of substrings based on a specified delimiter.
Syntax: explode(delimiter, string, limit)
delimiter
: Required. Specifies the character(s) to use for splitting the string.string
: Required. Specifies the string to be split.limit
: Optional. Specifies the maximum number of elements to include in the resulting array.
explode() example
$str = "The quick brown fox jumped over the lazy dog.";
$words = explode(" ", $str);
print_r($words);
In this example, the string “The quick brown fox jumped over the lazy dog” is split at every space character. The resulting array $words
will contain the following elements:
Array ( [0] => The [1] => quick [2] => brown [3] => fox [4] => jumped [5] => over [6] => the [7] => lazy [8] => dog. )
fprintf()
The PHP string function fprintf()
writes a formatted string to a specified stream. It returns the number of characters written, or false on error.
Syntax: fprintf ( resource $handle , string $format [, mixed $args [, mixed $... ]] ) : int|false
The first argument, $handle
, is the stream to which the string will be written. This can be a file handle, network socket, or any other stream resource created by fopen()
or fsockopen()
.
The second argument, $format
, is the format string. This can contain format specifiers similar to those in printf()
.
The third and subsequent arguments are optional, and contain the values to be inserted into the format string. These can be variables, constants, or expressions.
fprintf() example
This example demonstrates how to use fprintf()
to write a formatted string to a text file:
$file_handle = fopen("output.txt", "a");
$count = 3;
fprintf($file_handle, "There were %d errors.\n", $count);
fclose($file_handle);
This will write the string “There were 3 errors.” to a file called output.txt
. If the file doesn’t exist, it will be created. If it does exist, the new string will be appended to the end.
get_html_translation_table()
The get_html_translation_table()
function in PHP retrieves the translation table which is used to translate HTML special characters to their corresponding HTML entities.
The function takes two optional parameters:
$flags
: It is used to specify one or more of the following flags:
HTML_ENTITIES
: This will result in the returned array including ISO-8859-1 entities.HTML_SPECIALCHARS
: This will result in the returned array including special characters.
$encoding
: It’s used to specify the character encoding to be used for the returned array.
get_html_translation_table() example
Here is an example code snippet that demonstrates the use of get_html_translation_table()
function:
$table = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES, "UTF-8");
print_r($table);
This code retrieves the translation table for HTML entities and prints it to the screen. The table returned will contain both HTML and special characters encoded in UTF-8.
Note: The returned table will contain an array where the keys are the ASCII values of the characters and the values are the corresponding entities.
hebrev()
The hebrev()
function is a built-in function in PHP which converts Hebrew text to visual text which can be displayed correctly on a web page. With this function, text that is written from right to left (RTL) can be displayed correctly.
Syntax: hebrev (string $hebrew_text)
Parameters:
$hebrew_text
: Required. Specifies the Hebrew text to be converted into visual text.
This function returns the visual text representation of the Hebrew text.
hebrev() example
$string = "גאווה";
echo hebrev($string);
Output: להגן
hebrevc()
The hebrevc()
function is used to convert Hebrew text that is written right-to-left and contains logical sequences into displayable text. This function is similar to the hebrev()
function, but it also adds HTML character entities to preserve the logical order of the Hebrew text.
The syntax for the hebrevc()
function is: string hebrevc ( string $hebrew_text )
Here, $hebrew_text
is the Hebrew text to be converted.
hebrevc() example
Here is an example of how to use the hebrevc()
function:
$hebrew_text = "בעז המלך ואת הלבנה קם גבור משיח בימיו";
echo hebrevc($hebrew_text);
This will output the following:
םויימיב הידמש רובג םק ןהבל את קם ךורי רובוע
As you can see, the hebrevc()
function has converted the original Hebrew text into a format that can be displayed correctly on a web page.
hex2bin()
The hex2bin()
function is a built-in function in PHP which accepts a hexadecimal encoded string as an argument and converts this string to a binary string.
The function is useful when working with binary data that has been encoded in hexadecimal format, and allows you to convert the data back into its binary form.
Parameters:
- $hex_string`. Required. Specifies the hexadecimal string to be converted.
The hex2bin()
function returns the binary string corresponding to the supplied hexadecimal string.
hex2bin() example
$hex_string = "48656c6c6f20576f726c64";
$binary_string = hex2bin($hex_string);
echo $binary_string; // Output: "Hello World"
htmlspecialchars_decode()
The htmlspecialchars_decode()
function is a built-in PHP function that converts special HTML entities back to their corresponding characters.
It converts special HTML entities such as &
, <
, >
, "
, and '
back to their original characters. This function is useful when you want to display user-generated content that may contain special characters in a web page or email message.
The syntax for the htmlspecialchars_decode()
function is as follows:
string htmlspecialchars_decode ( string $string , int $flags = ENT_COMPAT | ENT_HTML401 , string|null $encoding = ini_get("default_charset") )
Parameters:
string
: Required. The input string that you want to decode.flags
: Optional. Specifies the quote_style parameter, which determines how quotes are handled. Use ENT_QUOTES to convert both double and single quotes, ENT_COMPAT to convert double quotes only (default), and ENT_NOQUOTES to not convert any quotes.encoding
: Optional. Specifies the character set to use for the input string (default is the value of the default_charset directive in thephp.ini
file).
htmlspecialchars_decode() example
Here’s an example of how to use the htmlspecialchars_decode()
function:
$string = "I love PHP &amp; MySQL!"; echo htmlspecialchars_decode($string);
In this example, the htmlspecialchars_decode()
function converts the & entity back to an ampersand character, so the output will be I love PHP & MySQL!
.
Note that if you want to convert special characters in a string to their corresponding HTML entities, you can use the htmlspecialchars()
function instead.
htmlspecialchars()
The PHP string function htmlspecialchars()
is used to convert special characters into their corresponding HTML entities. This function is mainly used to prevent cross-site scripting (XSS) attacks.
htmlspecialchars() example
Here is a working code example of how to use htmlspecialchars()
function:
$text = 'This is a **strong** text';
echo htmlspecialchars($text);
This will produce the following output:
This is a <strong>strong</strong> text
As you can see, the HTML tags are converted into their corresponding HTML entities, which prevents them from being interpreted as actual HTML tags by the browser.
implode()
The PHP implode()
function is used to join an array of strings to form a single string separated by a specified delimiter. This function takes two parameters; the first parameter is the delimiter to be used while joining the strings while the second parameter is the array of strings to be joined.
The implode()
function can be used in situations where you need to generate a string value from an array of data.
implode() example
$fruits = array('Apple', 'Banana', 'Mango', 'Orange');
$fruit_string = implode(", ", $fruits);
echo $fruit_string;
In this example, we have an array of strings (fruits) that we want to join together into a single string using the implode()
function. We pass a delimiter of “, ” as the first parameter to specify that each string should be separated by a comma and space. The resulting string is then saved in the $fruit_string
variable and finally printed out using the echo statement.
join()
The PHP string function join()
is used to join the elements of an array into a single string, leaving a specified delimiter between each element.
The syntax for the join()
function is as follows: join(delimiter, array)
.
Where “delimiter” is the string that is used to separate the elements in the returned string, and “array” is the array containing the elements to be joined.
join() example
Here’s an example of how the join()
function can be used:
$fruits = array("apple", "orange", "banana");
$fruit_list = join(", ", $fruits);`
echo $fruit_list;
In this example, the join()
function takes the array of fruits and creates a string that separates each fruit with a comma and a space. The resulting string, stored in the $fruit_list
variable, is then displayed using the echo statement.
Output: apple, orange, banana
lcfirst()
The PHP lcfirst()
function is used to convert the first character of a string to lowercase.
The syntax for using the lcfirst()
function is lcfirst(string $string)
.
The lcfirst()
function accepts only one parameter:
string
(required) – The string to convert.
The lcfirst()
function returns the modified string with the first character converted to lowercase.
lcfirst() example
The following example shows how to use the lcfirst()
function:
$string = 'Hello World!';
echo lcfirst($string); // Output: hello World!
levenshtein()
The levenshtein()
function calculates the difference between two strings, i.e. the number of changes required to transform one string to another. It returns an integer which represents the number of changes required.
levenshtein() example
$word1 = "kitten";
$word2 = "sitting";
$changes = levenshtein($word1, $word2);
echo "Number of changes required: " . $changes;
This would output: Number of changes required: 3
.
localeconv()
The PHP String Function localeconv()
is used to get numeric formatting information (such as decimal point, thousands separator, and currency symbol) as per the current locale settings.
Syntax: localeconv()
.
localeconv() example
$locale_info = localeconv(); print_r($locale_info); ?-->
Output:
Array
(
[decimal_point] => .
[thousands_sep] => ,
[int_curr_symbol] => USD
[currency_symbol] => $
[mon_decimal_point] => .
[mon_thousands_sep] => ,
[positive_sign] =>
[negative_sign] => -
[int_frac_digits] => 2
[frac_digits] => 2
[p_cs_precedes] => 1
[p_sep_by_space] => 1
[n_cs_precedes] => 1
[n_sep_by_space] => 1
[p_sign_posn] => 3
[n_sign_posn] => 0
[grouping] => Array
(
[0] => 3
)
)
In the above example, we have used the localeconv()
function to fetch the numeric formatting information for the current locale setting. We have then printed the returned array using the print_r()
function.
ltrim()
The ltrim()
function in PHP is used to remove white spaces or other predefined characters from the left side of a string. It returns a new string after removing the characters from the beginning of the string.
Syntax: ltrim(string, characters)
Parameters:
string
: Required. Specifies the string to be trimmed.characters
: Optional. Specifies the characters to be removed. Default value is space character.
Returns a string after removing the characters from the beginning (left side) of the input string.
ltrim() example
Remove spaces from the beginning of the string using ltrim()
:
$string = " Hello World! ";
echo "Original String: " . $string . "
";
// Removing white spaces from the beginning of string
$string_new = ltrim($string);
echo "New String: " . $string_new;
Output:
Original String: Hello World!
New String: Hello World!
md5_file()
The PHP string function md5_file()
is used to calculate the MD5 hash of a given file.
The MD5 hashing algorithm is a widely used cryptographic function that is commonly used to verify the integrity of files. The md5_file()
function takes the file path as its parameter and returns the MD5 hash of the file.
md5_file() example
Here’s an example of using the md5_file()
function in PHP:
$file_path = "example.txt";
$file_md5 = md5_file($file_path);
echo "The MD5 hash of the file is: " . $file_md5;
In this example, we are calculating the MD5 hash of a file named example.txt
. The md5_file()
function is called with the file path as its parameter, and the resulting MD5 hash is assigned to the $file_md5
variable.
Finally, the script outputs the MD5 hash of the file using the echo statement.
md5()
The md5()
function in PHP is used to calculate the MD5 hash of a string. It returns a 32-character string consisting of hexadecimal characters.
Syntax: md5(string, raw_output);
.
Parameters:
string
(required): Specifies the string to be hashed.raw_output
(optional): If set totrue
, the function will return raw binary format with each character being a byte. Default isfalse
.
md5() example
$original_string = "This is a sample string.";
$hashed_string = md5($original_string);
echo "Original string: {$original_string}
";
echo "Hashed string: {$hashed_string}";
?>
Output:
Original string: This is a sample string.\
Hashed string: 1295819264d9b9c36fecbb4b7f2e4c9
Note: The md5()
function is not considered a secure way to store passwords as the hash can easily be decrypted using modern methods of cracking. It is recommended to use stronger encryption algorithms such as bcrypt or Argon2 for password storage.
metaphone()
The PHP metaphone()
function calculates the metaphone key of a given string. The metaphone key is the phonetic representation of an input string. It returns a string based on the input string, and two similar sounding strings should return the same key. The metaphone algorithm processes English words and attempts to reduce their spelling to a phonetic code that matches the way they sound when spoken.
For example, search
and surge
will have the same metaphone key SRJ
, as they sound similar.
The metaphone()
function takes two parameters:
string:
Required. Specifies the string to calculate the metaphone key for.phonemes:
Optional. Specifies the maximum number of phonemes for the metaphone key. The default value is 0, which means that the function calculates the phonemes for the whole string. If the phonemes parameter is specified, only the specified number of phonemes are returned in the key.
The metaphone()
function returns the metaphone key of a given string.
metaphone() example
<?php
$str1 = 'search';
$str2 = 'surge';
$str3 = 'the';
echo metaphone($str1); // Outputs: SRJ
echo metaphone($str2); // Outputs: SRJ
echo metaphone($str3); // Outputs: 0
?>
money_format()
The money_format()
function is a built-in function in PHP that returns a formatted string of a given number. Specifically, it converts a number to a currency format that is suitable for display.
The function takes two arguments:
-
format: a string that specifies the format of the output. This string can contain special characters that are replaced with information about the number, such as the currency symbol, decimal separator, and thousands separator.
-
number: the number that is being formatted
money_format() example
Here’s an example of how the money_format()
function can be used:
$number = 1234.56; setlocale(LC_MONETARY, 'en_US'); echo money_format('%i', $number) . "\n";
In this example, the $number variable is set to 1234.56, and the setlocale()
function is used to set the locale to US English. The money_format()
function is then called with the format string %i
and the $number
variable as arguments. The result of this function call is a string that represents the number in US currency format, including the dollar sign and thousands separator. The output of this code would be $1,234.56
.
Note that the behavior of the money_format()
function can be affected by the locale that is set on the system or server. Additionally, this function may not be available on all systems, depending on how PHP was compiled or installed.
nl_langinfo()
The PHP string function nl_langinfo()
returns specific locale information. This function is used to access the locale information. The locale information may relate to monetary, numeric, or other formats. The nl_langinfo()
function is a built-in function that returns information about the given element. The returned information is according to the locale that is set in the system.
The syntax for the nl_langinfo()
function is nl_langinfo(item)
.
The item
is an integer parameter that is used to access the locale information. The item
specifies the type of information required.
The item
parameter is described as below:
RADIXCHAR
: Radix character ofsprintf()
floating point conversions in the current locale.THOUSEP
: Thousands separator of locale conv. ofsprintf()
, etc.YESEXPR
: Affirmative response expression for yes/no queries in the current locale.NOEXPR
: Negative response expression for yes/no queries in the current locale.
The nl_langinfo()
function returns a string that represents the value associated with the information requested. It returns FALSE if item
doesn’t exist.
nl_langinfo() example
Here’s an example of nl_langinfo()
function:
$radix_char = nl_langinfo(RADIXCHAR);
$thousands_sep = nl_langinfo(THOUSEP);
echo "Radixchar: " . $radix_char . "
";
echo "Thousep: " . $thousands_sep;
In the above example, nl_langinfo()
is used to access the locale information.
nl2br()
The nl2br()
function is a built-in function in PHP, which is used to insert HTML line breaks (
) in front of all newlines (\n) in a string. It is used to preserve the line breaks in the text, so that when the string is displayed on a website, the line breaks are visible.
Syntax: nl2br(string, is_xhtml)
.
Where:
string
: Required. Specifies the input string.is_xhtml
: Optional. Specifies whether to use XHTML compatible line breaks. Possible values are true or false. Default is false.
nl2br() example
$str = "This is a \nnew line.";`
echo nl2br($str);
Output:
This is a
new line.
number_format()
The PHP number_format()
function is used to format a given number with grouped thousands, decimal point and decimal digits.
The function takes two mandatory parameters:
number
: The number to be formatted.decimals
: The number of decimal points to be displayed (optional). By default it is 0.
There are also two optional parameters:
dec_point
: The character used as the decimal point separator (optional). By default it is “.”.thousands_sep
: The character used as the thousands separator (optional). By default it is “,”.
number_format() example
Here’s an example of how to use the number_format()
function:
$num = 123456.789;
echo number_format($num); // Output: 123,457
$num = 123456789.12345;
echo number_format($num, 2, ".", "-"); // Output: 123,456,789.12
In the first example, the function formats the number by adding commas to separate every three digits. In the second example, the function formats the number by adding a dash as the separator and displaying two decimal points.
ord()
The PHP string function ord()
returns the ASCII value of the character passed as an argument. ASCII (American Standard Code for Information Interchange) is a character encoding standard that assigns unique numbers to each character in the alphabet. The ord()
function can be used to convert any character to its ASCII value.
ord() example
Here’s a code example that uses the ord()
function:
$value = 'A';
$ascii_value = ord($value);
echo "The ASCII value of $value is $ascii_value";
The output of this code will be The ASCII value of A is 65
.
parse_str()
The parse_str()
function is a built-in string function in PHP used to parse a string into variables. It’s used to convert a query string or URL-encoded string into an associative array. This function can be useful when working with data sent via the HTTP GET or POST methods.
Syntax:
parse_str(string $string, array &$output [, mixed $parseType = parse_str_type ]): void
The parse_str()
function takes two mandatory parameters and one optional parameter:
string
: The input string to be parsed.&$output
: An array to store the output. The variables extracted will be appended to this array.$parseType
: An optional parameter, allowing you to specify how variables returned byparse_str()
are added to the output array. Valid values are:
parse_str() example
Let’s say we have a string containing a URL-encoded query string and we want to extract the variables and values into an associative array:
$url = "https://www.example.com/search.php?q=php+programming&limit=10&page=2";
parse_str(parse_url($url, PHP_URL_QUERY), $output);
var_dump($output);
This would output:
array(3) {
["q"]=>
string(15) "php programming"
["limit"]=>
string(2) "10"
["page"]=>
string(1) "2"
}
print()
The print()
function in PHP is used to output one or more strings. It is a language construct and not a function, so you don’t need to use parentheses when you use it. The print()
function cannot be used in an expression and always returns 1
.
print() example
Here’s a code example using the print()
function:
$message = "Hello, world!";
print($message);
In this example, the print()
function is used to print the string “Hello, world!” which is stored in the variable $message. This will output “Hello, world!” on the page.
printf()
The PHP String Function printf()
is used to format and output strings in a specific way. It allows you to insert variables or values into a string, specify how they should be formatted, and then output the resulting formatted string.
The printf()
function takes a format string as its first argument, which specifies how the output should be formatted. This format string can contain placeholders, which are indicated by %
followed by a letter that specifies the type of value that should be inserted.
For example, %s
is used to represent a string value, %d
is used to represent an integer value, and %f
is used to represent a floating-point value.
printf() example
Here’s an example of how to use the printf() function:
$number = 42;
$string = "Hello, world!";
$float = 3.14159;`
// Output: "The answer is 42"
printf("The answer is %d", $number);
// Output: "Hello, world! 3.14159"
printf("%s %f", $string, $float);
quoted_printable_decode()
The quoted_printable_decode()
function in PHP is used to decode a quoted-printable string. Quoted-printable encoding is used to convert non-printable and special characters into printable characters. This function converts the printable characters back to their original form.
quoted_printable_decode() example
This example demonstrates how to use the quoted_printable_decode()
function in PHP:
$encoded_string = "=48=65=6c=6c=6f=2c=20=57=6f=72=6c=64=21";
$decoded_string = quoted_printable_decode($encoded_string);`
echo $decoded_string;
The above code will output Hello, World!
.
quoted_printable_encode()
The PHP String Function quoted_printable_encode()
encodes a given string in quoted-printable format. This function returns a string in which all non-printable characters (other than newline and carriage return) are replaced by their hexadecimal equivalents and are then preceded by the =
character.
Syntax: quoted_printable_encode($string)
.
quoted_printable_encode() example
$string = "Hello, World! This is a test string.";
$encoded_string = quoted_printable_encode($string);
echo $encoded_string;
Output: Hello,=20World!=20This=20is=20a=20test=20string
.
quotemeta()
The PHP string function quotemeta()
is used to add a backslash before any character that is non-alphanumeric. This function is typically used when working with regular expressions to ensure that special characters are treated as literals.
Syntax: string quotemeta ( string $str )
.
Parameters:
str
: The input string that will be escaped.
The function returns the string with backslashes before non-alphanumeric characters.
quotemeta() example
$string = "Hello [email protected]#World!";
echo quotemeta($string);
Output: Hello\ \[\email protected]\#World\!
rtrim()
The rtrim()
function in PHP is used to remove white spaces or other predefined characters from the right side of a string. This function takes a string and the character that needs to be removed from the right as input and returns the modified string.
Syntax: rtrim(string,character)
.
Parameters:
string
: Specifies the input string.character
: Specifies the characte or set of characters to be removed from the right of the string.
The rtrim()
function in PHP returns the modified string after removing the white spaces or other predefined characters from the right side of the input string.
rtrim() example
$str = " Hello World! ";
echo "Original String: '$str'";
echo "
";
$trimmed_str = rtrim($str);
echo "String after removing white spaces: '$trimmed_str'";
echo "
";
$trimmed_str = rtrim($str, "!");
echo "String after removing '!' from the right: '$trimmed_str'";
?>
Output:
Original String: ' Hello World! '
String after removing white spaces: ' Hello World!'
String after removing '!' from the right: ' Hello World'
Wrap Up
These are the main PHP string functions you need to know. For a full list visit the PHP manual.
To see our full list of extensive PHP books and courses join SitePoint Premium.