PHP String

PHP

In this tutorial we will learn about PHP string.

What is a string?

In simple words, string is a sequence of characters.

In PHP we create a string by enclosing characters inside single quote and double quote. Following are some examples of string.

$name = 'Yusuf Shakeel';
$country = "India";

Note!
When we enclose a string in single quotes PHP uses it as exactly types. On the other hand, if we enclose a string in double quotes then we get some extra features like including variable name and escape sequence within the string.

In the following example we are using single quote.

$x = 10;

//single quote string
echo 'Value of x = ' . $x;

The above code will print "Value of x = 10".

By using the double quote we can place the variable $x inside as shown below.

$x = 10;

//single quote string
echo "Value of x = $x";

The above code will print "Value of x = 10". This is because when $x is encountered inside the double quote, PHP replaces it with the value.

Another way of achieving the same result is by enclosing the variable in curly braces.

$x = 10;

//single quote string
echo "Value of x = {$x}";

The above code will also generate the same output "Value of x = 10".

Escape Sequence

Escape sequences are special characters that we use in a string. They have a special meaning and start with \ character. For example if we want to show horizontal tab we use \t escape sequence.

Following are some of the commonly used escape sequence.

Escape SequenceMeaning
\'Single quote
\"Double quote
\\Backslash character
\nLine feed character
\rCarriage return character
\tHorizontal tab

Concatenate string

We can concatenate two strings using the dot operator. Following are some examples.

$first_name = "Yusuf";
$last_name = "Shakeel";

$full_name = $first_name . " " . $last_name;

echo "Hello, I am {$full_name}.";

The above code will print "Hello, I am Yusuf Shakeel."

Length of the string - strlen()

We use the strlen() function to find the length of the string i.e., total number of characters in the string.

$month = "October";

$len = strlen($month);

echo "Total number of characters = {$len}";

The above code will print "Total number of characters = 7".

Accessing string characters

A string consists of a sequence of characters. The first character starts from index 0.

For example, consider the following string "Hello". It consists of 5 characters. The first character "H" is at index 0. The second character "e" is at index 1. And the last character "o" is at index 4.

In order to print a character of a string at index N we write $x[N] where $x is the variable holding the string value.

In the following example we will print the third character. Note! the third character is at index 2.

$month = "October";

echo $month[2];		//output t

Search string - strstr()

To find if a text occurs within a given string we use the strstr() function. We pass two parameters. The first parameter is the string to search through. The second parameter is the text to search.

If the text is found the function will return portion of the string from the start of the found text till the end of the string. Otherwise, it will return false.

$text = "lo";
$st = "Hello World!";

echo strstr($st, $text);	//lo World!

The function strstr() is case sensitive. For case insensitive use the function stristr.

Find the position - strpos()

This function will search the given text in the string and will return the index of the first character of the text if it is found otherwise, it will return false.

$text = "el";
$string = "Hello World!";

echo strpos($string, $text);

The above code will print 1 as "el" is found at index 1. Remember, indexing starts from 0.

The function strpos() is case sensitive. For case insensitive use the function stripos.

Find the position from reverse - strrpos()

This function will return the first occurance index of the text in the string from reverse.

$text = "l";
$string = "Hello World!";

echo strrpos($string, $text);

The above code will print 9 as it is the index of the first occurance of "l" from reverse in the string.

The function strrpos() is case sensitive. For case insensitive use the function strripos.

Count text in string - substr_count()

This function will count the total number of times text occurred in the string.

$text = "code";
$string = "I love code. You love code. We love code!";

echo substr_count($string, $text);

The above code will print 3.

If the text is a part of a word then it will also be considered.

$text = "he";
$string = "He and She";

echo substr_count($string, $text);

The above code will print 1. This is because "he" is present in the word "She". Also note "He" is not equal to "he" because of case differences.

Search for characters - strpbrk()

This function checks if a string contains any one of the characters. If match is found then this function will return portion of the string from the first matched character till the end of the string. Otherwise it will return false.

$char = "@#!%";

$string = "Hello! This is a sample #string.";

echo strpbrk($string, $char);

The above code will return "! This is a sample #string." as $string contains the char ! and #.

Replace all occurance of a string - str_replace()

This function will replace all occurance of one string in another.

The original string remains unchanged and only a modified copy is returned.

$string = "Java is a programming language. Java is awesome!";

$replace = "Java";

$replace_with = "PHP";

echo str_replace($replace, $replace_with, $string);

The above code will print "PHP is a programming language. PHP is awesome!".

The function str_replace() is case sensitive. For case insensitive use the function str_ireplace.

Replacing a portion of a string - substr_replace()

This function will replace a specific portion of the target string.

The original string remains unchanged and only a modified copy is returned.

$string = "8 A.M. radio!";

$replacement = "P.M.";

$start_index = 2;

echo substr_replace($string, $replacement, $start_index);

The above code will print the following "8 P.M." as it replaces all characters starting from index 2 till the end of string $string with $replacement "P.M.".

The substr_replace() replaces all characters with $replacement from the $start_index till the end of the string.

If we want to replace only a portion of the string then we can pass the fourth parameter.

$string = "8 A.M. radio!";

$replacement = "P.M.";

$start_index = 2;

$limit = 4;

echo substr_replace($string, $replacement, $start_index, $limit);

The above code will start replacing all the characters from index 2 and will place only 4 characters with "P.M." So, the output of the above code will be "8 P.M. radio!".

Character replacement - strtr()

This function takes 3 parameters, the string to work on, string of characters to replace and the character set to replace with.

The original string remains unchanged and only a modified copy is returned.

$string = "Hello World!";
$target_characters_string = " !";
$replacement_characters = "-_";

echo strtr($string, $target_characters_string, $replacement_characters);

The above code will replace all the " " space character with "-" hyphen and all the "!" exclamation character with "_" underscore character. So the output of the above will be "Hello-World_";

Uppercase - strtoupper()

To convert all the characters of a string to uppercase we use strtoupper() function.

$str = "Hello!";

echo strtoupper($str);

The above code will print "HELLO!".

Lowercase - strtolower()

To convert all the characters of a string to lowercase we use strtolower() function.

$str = "Hello!";

echo strtolower($str);

The above code will print "hello!".

To make first character Uppercase - ucfirst()

This function will convert the first character of the string to uppercase.

$str = "hello!";

echo ucfirst($str);

The above code will print "Hello!".

To make first character Lowercase - lcfirst()

This function will convert the first character of the string to lowercase.

$str = "HELLO!";

echo lcfirst($str);

The above code will print "hELLO!".

To make first character of every word Uppercase - ucwords()

This function will convert the first character of every word in a string to uppercase.

$str = "hello world!";

echo ucwords($str);

The above code will print "Hello World!".

Trim string - trim()

This function will remove white spaces from the beginning and end of the string.

$str = "   Hello World!   ";

echo trim($str);

The above code will print "Hello World!".

Trim left - ltrim()

This function will remove white spaces from the beginning of the string.

$str = "   Hello World!   ";

echo ltrim($str);

The above code will print "Hello World! ".

Trim right - rtrim()

This function will remove white spaces from the end of the string.

$str = "   Hello World!   ";

echo rtrim($str);

The above code will print " Hello World!".

String padding - str_pad()

This function is used to pad a string with characters.

$str = "Hi";
$width = 5;

echo str_pad($str, $width);

The above code will pad the string $str with white space (default) and max length will be 5. So the output will be "Hi ".

Default padding is to the right (at the end) of the string and default character used for padding is space.

To pad the string with a specific character we pass the third parameter.

$str = "Hi";
$width = 5;

echo str_pad($str, $width, "*");

Output will be "Hi***".

The width decide the final length.

$str = "Hi";
$width = 5;

echo str_pad($str, $width, "1245");

Output will be "Hi123". As the final length for the string is 5 so last two character "45" is truncated.

We can pass the fourth parameter to control the padding position.

$str = "Hi";
$width = 5;

echo str_pad($str, $width, "**", STR_PAD_RIGHT);

This will perform right padding and the output will be "Hi***".

$str = "Hi";
$width = 5;

echo str_pad($str, $width, "**", STR_PAD_LEFT);

This will perform left padding and the output will be "***Hi".

$str = "Hi";
$width = 5;

echo str_pad($str, $width, "**", STR_PAD_BOTH);

This will perform right padding and the output will be "*Hi**".

String formatting - printf()

The printf() function is used to print the output. In the following example we are going to print "Hello World!".

printf("Hello World!");

We can also use type specifier in printf() to specify the type of the variable in order to format the output.

In the following example we have an integer variable $x set to 10. We are printing the value of $x variable using the type specifier %d.

$x = 10;

printf("Value of x = %d", $x);

Output of the above code is "Value of x = 10". The value of $x is put into the place of %d. The type specifier %d tells us that the type of $x is integer.

Following are the list of type specifier with their meaning.

Type specifierMeaning
%bTreat the argument as integer and format it as binary number.
%cTreat the argument as integer and format it as character with that ASCII value.
%dTreat the argument as integer and format it as a signed decimal number.
%eFormat the argument as scientific notation. Example 2e+9
%fFormat the argument as floating point number.
%oTreat the argument as integer and output it as octal number.
%sFormat the argument as string.
%uTreat the argument as integer and output it as unsigned decimal number.
%xTreat the argument as integer and output it as hexadecimal number in lowercase.
%XTreat the argument as integer and output it as hexadecimal number in uppercase.
%%Display the % symbol. No argument is required for this.

Example

$name = "Yusuf Shakeel";
$time = "10am";
$day = "Sunday";

printf("%s will upload his new YouTube video at %d on %s.", $name, $time, $day);

Output of the above code is "Yusuf Shakeel will upload his new YouTube video at 10 on Sunday."

Printing signed numbers using printf()

By default printf() will display negative numbers with a (-) sign but a positive number is not shown with a (+) sign. To display the proper sign use the following.

printf("%+d", 10);	//this will print "+10"
printf("%+d", -10);		//this will print "-10"

Padding output using printf()

We can also pad output by inserting padding specifier.

In the following example we pad the numbers with lead 0s and total number of characters will be 6.

$x = 10;
printf("%06d", $x);

Output: 000010

To pad with special characters use the apostrophe (') sign followed by the character you want to use.

In the following example we pad the numbers with lead #s and total number of characters will be 6.

$x = 10;
printf("%'#6d", $x);

Output: ####10

Padding by default is always at the left side. To add padding at the right side we use the (-) sign.

In the following example we pad the numbers with trailing #s and total number of characters will be 6.

$x = 10;
printf("%'#-6d", $x);

Output: 10####

Number precision using printf()

We can also limit the number of decimal places we want in the output using precision specifier.

In the following example we print the value of PI = 22/7.

$pi = 22/7;
printf("%f", $pi);

Output: 3.142857

To limit the decimal place to TWO digits we use %.2f

$pi = 22/7;
printf("%.2f", $pi);

Output: 3.14

To pad with lead 0s and limit the total number of characters to 5 and also limit decimal place to TWO we use the following.

$pi = 22/7;
printf("%05.2f", $pi);

Output: 03.14

For storing result use sprintf()

To store the result in a variable for later use we use the sprintf() function. This function is exactly the same as printf() but instead of printing the result it returns the resulting string.

$time = 8;
$txt = "Radio!";

$str = sprintf("This is %d A.M. %s", $time, $txt);

The above code will save "This is 8 A.M. Radio!" in variable $str.