Working with String variables

Posted by tutor | Posted in PHP Tutorial | Posted on 03-08-2010-05-2008

0

A string variable is used to store and manipulate character strings.

PHP provides some pre defined functions to manipulate string variables. There are someoperators also which directly work on strings.

For eg:

<?php
$txt=”Its PHP”;
echo $txt;
?>

Output:

Its PHP

We can use strings directly within double quotes or we can assign them to some variable and can use them through variables.

The Concatenation Operator

PHP provides an operator to manipulate string variables directly. This is called the concatenation operator represented by a “.” (dot).
The concatenation operator (.), as the name implies, concatenates two strings, ie it joins two or more strings.

For eg:

<?php
$txt1=”Its PHP!”;
$txt2=” So easy to use!”;
echo $txt1 . $txt2;
?>

Output:

Its PHP! So easy to use!

The strlen() function

Like in other languages PHP defines the strlen() function, which returns the length of a string.

For eg:

<?php
echo strlen(“Its PHP!”);
?>

Output:

8

This function can be useful in various string operations like matching two strings or finding some string in a large text where the loop counter should iterate till the last character of the text only. Various other applications can also use this function.

The strpos() function

The strpos() function searches a given character within a string.

If the character is found, this function will return the position of the first match. If no match is found, it will return FALSE.

For eg:

<?php
echo strpos(“Its PHP!”,”PHP”);
?>

Output:

4

The position of the string “world” is 6, as the counter starts from 0.