Latest web development tutorials

PHP string variable

String variable is used to store and manipulate text.


PHP string variable

String variable is used to contain the character values.

After you create a string we can manipulate it up. You can use directly in a function string, or store it in a variable.

In the following example, we create a string variable named txt and assigned to "Hello world!". We then output txt variable:

Examples

<? php
$ txt = "Hello world!" ;
echo $ txt;
?>

Running instance »

lampNote: When you assign a value to a variable text, please remember to add text value single or double quotes.

Now, let's look at some common string manipulation functions and operators.


PHP concatenation operator

In PHP, there is only one string operator.

Concatenation operator (.) Is used to connect the two string values.

The following example demonstrates how to connect together two string variables:

Examples

<? php
$ txt1 = "Hello world!" ;
$ txt2 = "What a nice day !";
.. echo $ txt1 "" $ txt2;
?>

The code above will output: Hello world What a nice day!!

Tip: In the above code, we have used twice concatenation operator. This is because we need to insert a space between two strings.


PHP strlen () function

Sometimes you know the length of the string value is useful.

strlen () function returns the length of the string (number of characters).

The following example returns the string "! Hello world" length:

Examples

<? php
echo strlen ( "Hello world!" );
?>

Running instance »

The code above will output: 12

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


PHP strpos () function

strpos () function is used to find a character or text within a specified string.

If a match is found in the string, the function will return the first matching character position. If no match is found, it returns FALSE.

"! Hello world" in the following examples find the text string "world":

Examples

<? php
echo strpos ( "Hello world!" , "world");
?>

Running instance »

The code above will output: 6

Tip: In the above example, the string "world" position 6. The reason is the cause of 6 instead of 7 is the position of the first character in the string is 0 instead of 1.


Complete PHP String Reference

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

This reference manual provides a brief description of each function and application examples!