PHP 5 Strings
String variables are used to store and process text.
String variables in PHP
String variables are used for values that contain characters.
After the string is created, we can manipulate it. You can use a string directly in a function or store it in a variable.
In the following example, we create a string variable named txt and assign it the value "Hello world!" Then we output the value of the txt variable:
Now let's take a look at some common functions and operators for manipulating strings.
PHP concatenation operator
In PHP, there is only one string operator.
The concatenation operator (.) concatenates two string values.
The following example shows how to concatenate two string variables:
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
The above code will output: Hello world! What a nice day!
Tip: In the code above, we have used the concatenation operator twice. This is because we need to insert a space between the two strings.
PHP strlen () function
Sometimes it is useful to know the length of a string value.
The strlen () function returns the length (in bytes) of a string.
The following example returns the length of the string "Hello world!":
echo strlen("Hello world!");
The above code will output: 12
Tip: strlen () is often used in loops and other functions, because it is important to determine when the string ends at that time. (For example, in a loop, we need to end the loop after the last character in the string.)
PHP strpos () function
strpos () function is used to find a character or a specified piece of text within a string.
If a match is found in the string, the function returns the character position of the first match. If no match is found, FALSE is returned.
The following example finds the text "world" in the string "Hello world!":
echo strpos("Hello world!","world");
The above code will output: 6
Tip: In the example above, the position of the string "world" is 6. The reason why it is 6 instead of 7 is that the position of the first character in the string is 0, not 1.
Complete PHP String Reference Manual
For a complete reference manual of all string functions, please visit our PHP String Reference Manual.
This reference manual provides a brief description and application examples of each function!