Now that you know how to create strings in PHP, it’s time to try out some basic string operations. In this tutorial you learn how to:
- Join strings together
- Find out the length of a string, and
- Read and change individual characters within a string.
Joining strings
To join 2 or more strings together to make 1 long string, use the concatenation operator, which is a .
(dot). For example, to join 2 strings you could use:
$string1 = 'Hello, ';
$string2 = 'there!';
$string3 = $string1 . $string2;
echo $string3; // Displays "Hello, there!"
To join 3 strings you might write:
$string1 = 'Hello,';
$string2 = ' ';
$string3 = 'there!';
$string4 = $string1 . $string2 . $string3;
echo $string4; // Displays "Hello, there!"
Getting the length of a string
You can use PHP’s strlen()
function to retrieve the number of characters in a string:
$myString = 'Hello, there!';
echo strlen( $myString ); // Displays "13"
If you want to find out the number of words in a string, you can use str_word_count()
:
$myString = 'Hello, there!';
echo str_word_count( $myString ); // Displays "2"
Accessing characters within a string
To access a character in a string, write the string variable name followed by the character position, or index, in square brackets:
$myString = 'Hello, there!';
echo $myString[7]; // Displays "t"
You can change characters in a string using the same technique:
$myString = 'Hello, there!';
$myString[12] = '?';
echo $myString; // Displays "Hello, there?"
If you want to read a sequence of characters from a string, use PHP’s substr()
function. This takes the following arguments:
- The string.
- The position to start extracting characters. Use a negative number to count backwards from the end of the string.
- The number of characters to extract (optional). Miss out this argument to extract from the start position to the end of the string. You can also supply a negative number to miss out that many characters from the end of the string.
Here are some substr()
examples:
$myString = 'Hello, there!';
echo substr( $myString, 7 ) . "<br />"; // Displays "there!"
echo substr( $myString, 0, 5 ) . "<br />"; // Displays "Hello"
echo substr( $myString, -4 ) . "<br />"; // Displays "ere!"
echo substr( $myString, -6, -1 ) . "<br />"; // Displays "there"
You now know how to carry out basic operations on PHP strings. You’ve looked at joining strings together; how to find out the length of a string; and how to work with individual characters within a string. Happy coding!
Leave a Reply