Learning PHP (5) – Using built-in functions
June 12th, 2009 by admin | Filed under Learning PHP.I had promised myself that I would post every second day, but I didn’t know exactly where to go from what we have built up and I also became engaged, she said yes! So it has been crazy days.
But I’m happy, at least
I am going to continue with showing how to take use of some of the built-in string fuctions. These can be used to manipulate text variables that you might receive from the $_GET and $_POST variables.
Find occurrence of text in strings
You can for example use the function strstr() or stristr() if you want a cast-insensitive matching style.
Example
$mystring = 'this websites owner is nice';
if (strstr($mystring, 'website')) {
echo 'I found the word "website" in the string.';
}
I can use double quotes in the string because I have it enclosed in single quotes.
If I were to use single quotes it would unquote the string and generate a syntax error.
If you replace strstr with stristr in the example, it would
also give a match if $mystring contains the word ‘Website’ with an upper case W.
explode() strings
If you get a string such as “one,two,three,four,five,six” and you would rather have
it indexed in an array you can use the function explode() to achieve this.
The build-in function explode() will parse a string and split it based on the
argument you give the function. An example will follow:
$mystring = "one,two,three,four;five,six,seven";
$myarray = explode(",", $mystring);
var_dump($myarray);
The first argument to explode is the delimiting character, while the other
is the string that will be split into an array. The result of this would be:
array(6) {
[0]=>
string(3) “one”
[1]=>
string(3) “two”
[2]=>
string(5) “three”
[3]=>
string(9) “four;five”
[4]=>
string(3) “six”
[5]=>
string(5) “seven”
}
Notice that $myarray[3] contains four;five, this is due to a common
mistake.. it can be hard to overlook, so can you figure out why it does that?
Anyways, you should check out the documentation and try out some
of the functions, because they are really easy to use and implement.
Good luck!
Tags: array, built-in, explode, functions, learn php, Learning PHP, php, stristr, strstr

Follow me on Twitter