Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP String Variables

PHP String Variables


String variables are used to store and process text.


String variables in PHP

String variables are used to hold values containing characters.

After creating a string, we can operate on it. You can use the string directly in a function, or store it in a variable.

In the example below, we create a string variable named txt and assign it the value "Hello world!". Then we output the value of the txt variable:

Example

Run Example »

lamp **Note:** When you assign a text value to a variable, remember to add single or double quotes around the text value.

Now, let's look at some commonly used functions and operators for manipulating strings.


PHP Concatenation Operator

In PHP, there is only one string operator.

The concatenation operator . is used to join two string values together.

The example below demonstrates how to concatenate two string variables together:

Example

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 of a string (number of bytes).

The example below returns the length of the string "Hello world!":

Example

Run Example »

The above code will output: 12

**Tip:** strlen() is often used in loops and other functions, because then it is important to determine when the string ends. (For example, in a loop, we need to end the loop after the last character in the string.)


PHP strpos() Function

The 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 position of the first matched character. If no match is found, it returns FALSE.

The example below searches for the text "world" in the string "Hello world!":

Example

Run Example »

The above code will output: 6

**Tip:** In the example above, the position of the string "world" is 6. The reason it is 6 rather than 7 is that the position of the first character in a string is 0, not 1.


Complete PHP String Reference Manual

To view the complete reference manual of all string functions, please visit our PHP String Reference Manual.

This reference manual provides a brief description and application example for each function!