Working with Strings in PHP!
PHP Tutorial on working with strings
When using vales that contain characters you will use string variables to store them. This tutorial will only show a few of the most used functions and operations that are used to manipulate strings in PHP.
Using a String variable to output text
You can both use a string in a function or store it in a variable to be used throughout your website or script.
Below we will store a string to a variable named $title.
<?php
$title="Mofiki WorldWide";
echo $title;
?>
The output of the code above will be:
Mofiki WorldWide
In PHP (.) is the only operator that can be used (concatenation operator). We use this operator to put two strings together to create a steady stream of values. Below is an example of this in action.
<?php
$title1="Mofiki WorldWide";
$title2="Website Design and Development
echo $title1 . " " . $title2;
?>
This code would output:
Mofiki WorldWide Website Design and Development
The reason we used the (.) twice in the example above is so that we could enter a space between the two strings. Without this space the two strings would have ran together and the words WorldWide and Website would have been displayed as one word instead of 2 (i.e. WorldWideWebsite).
Using the strlen() function in PHP
The strlen() function is used if you want to return a strings length. For Example:
<?php
echo strlen("Mofiki WorldWide");
?>
The result would be: 16
More often then not this function is used to find the end of a string. You would use this in loops and additions to other functions.
Using the strpos() function in PHP
The strpos() function is useful when trying to find a character in a string. If no match is found then it will
return FALSE, although if one is found it will return the position of the first time it sees the match.
<?php
echo strpos("Mofiki WorldWide","WorldWide");
?>
This code would ouput: 7