Search
Sponsors

Posts Tagged ‘PHP’

Mastering Regular Expressions in PHP

Wednesday, February 27th, 2008

by Dennis Pallett
What are Regular Expressions?
A regular expression is a pattern that can match various text strings. Using regular expressions you can find (and replace) certain text patterns, for example “all the words that begin with the letter A” or “find only telephone numbers”. Regular expressions are often used in validation classes, because they are a really powerful tool to verify e-mail addresses, telephone numbers, street addresses, zip codes, and more.

In this tutorial I will show you how regular expressions work in PHP, and give you a short introduction on writing your own regular expressions. I will also give you several example regular expressions that are often used.
Regular Expressions in PHP
Using regex (regular expressions) is really easy in PHP, and there are several functions that exist to do regex finding and replacing. Let’s start with a simple regex find.

Have a look at the documentation of the preg_match function. As you can see from the documentation, preg_match is used to perform a regular expression. In this case no replacing is done, only a simple find. Copy the code below to give it a try.

<?php

// Example string
$str = "Let's find the stuff <bla>in between</bla> these two previous brackets";

// Let's perform the regex
$do = preg_match("/<bla>(.*)</bla>/", $str, $matches);

// Check if regex was successful
if ($do = true) {
// Matched something, show the matched string
echo htmlentities($matches['0']);

// Also how the text in between the tags
echo '<br />' . $matches['1'];
} else {
// No Match
echo "Couldn't find a match";
}

?>

After having run the code, it’s probably a good idea if I do a quick run through the code. Basically, the whole core of the above code is the line that contains the preg_match. The first argument is your regex pattern. This is probably the most important. Later on in this tutorial, I will explain some basic regular expressions, but if you really want to learn regular expression then it’s best if you look on Google for specific regular expression examples.

The second argument is the subject string. I assume that needs no explaining. Finally, the third argument can be optional, but if you want to get the matched text, or the text in between something, it’s a good idea to use it (just like I used it in the example).
The preg_match function stops after it has found the first match. If you want to find ALL matches in a string, you need to use the preg_match_all function. That works pretty much the same, so there is no need to separately explain it.

Now that we’ve had finding, let’s do a find-and-replace, with the preg_replace function. The preg_replace function works pretty similar to the preg_match function, but instead there is another argument for the replacement string. Copy the code below, and run it.

<?php

// Example string
$str = "Let's replace the <bla>stuff between</bla> the bla brackets";

// Do the preg replace
$result = preg_replace ("/<bla>(.*)</bla>/", "<bla>new stuff</bla>", $str);

echo htmlentities($result);
?>

The result would then be the same string, except it would now say ‘new stuff’ between the bla tags. This is of course just a simple example, and more advanced replacements can be done.

You can also use keys in the replacement string. Say you still want the text between the brackets, and just add something? You use the $1, $2, etc keys for those. For example:

<?php

// Example string
$str = "Let's replace the <bla>stuff between</bla> the bla brackets";

// Do the preg replace
$result = preg_replace ("/<bla>(.*)</bla>/", "<bla>new stuff (the old: $1)</bla>", $str);

echo htmlentities($result);
?>

This would then print “Let’s replace the new stuff (the old: stuff between) the bla brackets”. $2 is for the second “catch-all”, $3 for the third, etc.

That’s about it for regular expressions. It seems very difficult, but once you grasp it is extremely easy yet one of the most powerful tools when programming in PHP. I can’t count the number of times regex has saved me from hours of coding difficult text functions.

An Example
What would a good tutorial be without some real examples? Let’s first have a look at a simple e-mail validation function. An e-mail address must start with letters or numbers, then have a @, then a domain, ending with an extension. The regex for that would be something like this: ^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$

Let me quickly explain that regex. Basically, the first part says that it must all be letters or numbers. Then we get the @, and after that there should be letters and/or numbers again (the domain). Finally we check for a period, and then for an extension. The code to use this regex looks like this:

<?php

// Good e-mail
$good = "john@example.com";

// Bad e-mail
$bad = "blabla@blabla";

// Let's check the good e-mail
if (preg_match("/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/", $good)) {
echo "Valid e-mail";
} else {
echo "Invalid e-mail";
}

echo '<br />';

// And check the bad e-mail
if (preg_match("/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/", $bad)) {
echo "Valid e-mail";
} else {
echo "Invalid e-mail";
}

?>

The result of this would be “Valid E-mail. Invalid E-mail”, of course. We have just checked if an e-mail address is valid. If you wrap the above code in a function, you’ve got yourself a e-mail validation function. Keep in mind though that the regex isn’t perfect: after all, it doesn’t check whether the extension is too long, does it? Because I want to keep this tutorial short, I won’t give the full fledged regex, but you can find it easily via Google.

Another Example
Another great example would be a telephone number. Say you want to verify telephone numbers and make sure they were in the correct format. Let’s assume you want the numbers to be in the format of xxx-xxxxxxx. The code would look something like this:

<?php

// Good number
$good = "123-4567890";

// Bad number
$bad = "45-3423423";

// Let's check the good number
if (preg_match("/d{3}-d{7}/", $good)) {
echo "Valid number";
} else {
echo "Invalid number";
}

echo '<br />';

// And check the bad number
if (preg_match("/d{3}-d{7}/", $bad)) {
echo "Valid number";
} else {
echo "Invalid number";
}

?>

The regex is fairly simple, because we use d. This basically means “match any digit” with the length behind it. In this example it first looks for 3 digits, then a ‘-’ (hyphen) and finally 7 digits. Works perfectly, and does exactly what we want.

What exactly is possible with Regular Expressions?
Regular expressions are actually one of the most powerful tools in PHP, or any other language for that matter (you can use it in your mod_rewrite rules as well!). There is so much you can do with regex, and we’ve only scratched the surface in this tutorial with some very basic examples.

If you really want to dig into regex I suggest you search on Google for more tutorials, and try to learn the regex syntax. It isn’t easy, and there’s quite a steep learning curve (in my opinion), but the best way to learn is to go through a lot of examples, and try to translate them in plain English. It really helps you learn the syntax.

In the future I will dedicate a complete article to strictly examples, including more advanced ones, without any explanation. But for now, I can only give you links to other tutorials:
The 30 Minute Regex Tutorial
Regular-Expressions.info

About the Author

Dennis Pallett is a young tech writer, with much experience in ASP, PHP and other web technologies. He enjoys writing, and has written several articles and tutorials. To find more of his work, look at his websites at http://www.phpit.net, http://www.aspit.net and http://www.webdev-articles.com

using include files

Wednesday, February 27th, 2008

using include files
Include files

This tutorial shows how to use the include() function.

The include() function can be used to call an external file from your server or even a different server.

Syntax

The general syntax for a basic include is as follows

<?php include(”otherfile.txt”); ?>

This includes a file called otherfile.txt from the same directory on your server.

You can also use it like this

<?php include(”http//www.myothersite/otherfile.txt”); ?>

This means you can share the same file on more than one site .

Advantages

Well the advantages are obvious if you are site is growing. Imagine you have a site with 50 pages and you have designed a nice
navigation area but you have forgotten a download link. This would require 50 changes to your site but using an template with an
include file you would change the include file content and all the other pages would be updated

Basic Math Operators in PHP

Thursday, February 21st, 2008

Basic Math Operators

The basic math operators in PHP should be familiar to anyone with programming experience . The set of mathematical operators available are listed below.

Operator Description
+ The addition operator
- The subtraction operator , can also be used for negation like this -9
* The multiplication operator
/ the division operator
% the modulus operator , returns the remainder after division . For example 25 % 3 would give us 1 .

Here is an example

<?php
$number1 = 9;
$number2 = 4;
echo $number1 + $number2;
?>

Which produces the following
13

Incrementing

To increment a variable in PHP we do the following

$yearsindebt++;

This increments the $yearsindebt variable by one , we can also do the following .

$mybill += 20;

which is the same as saying $mybill = $mybill + 20;

Order Of Precedence

The math operators all have to obey an order of precedence which is used in mathematics . This often catches out beginners . Lets look at an example

$calc = 25 + 4 * 2;

What do you think the value of $calc is , well you could add 25 + 4 and get 29 then multiply by 2 and get 58 . Wrong . The rules of precedence say that multiplication gets calculated before addition so you get 4 * 2 is 8 and then 25 + 8 = 33 . 33 is the correct answer . A big difference from 58 .

At school I was taught to use BODMAS to help remember order of precedence this is basically Brackets , Division , Multiplication , Addition , Subtraction. What if you want to add the 25 + 4 first and then multiply this by 2 , well you can do the following.

$calc = (25 + 4) * 2;

Now the brackets get evaluated first because they come before multiplication in the order of precedence..

Variable Tutor part 2

Thursday, February 21st, 2008

Variable Tutor part 2

In part 2 we are going to deal with Data Types and Type Casting amongst other things.

Data Types

These are the data types which uses .

  • string ( text )
  • integer (numeric)
  • double(numeric)
  • array
  • object
  • unknown type

As you can see there are not as many data type are there are in some other languages , this in fact is a help to many a programmer . As a programmer you do not worry about setting these data types , PHP does it for you.

Strings

This is the data type that stores text , this can be single characters , words and even complete sentences . How many strings do you think we have below .

$mywages = “not much”;
$intloan = “3000″;

If you said one you are wrong , if you said two give yourself a pat on the back . remember we enclosed the number with quotation marks so PHP treats this as text information .

Concatenation

This means adding one string to another . If you are coming from another programming language this may (will) catch you out from time to time . In PHP we use the period ( . ) to concatenate strings.For example

$firstname = “Bill”;
$secondname = “Gates”;
echo $firstname . $secondname;

would print on the screen BillGates

Numeric Values

There are 2 different types of numerical data types in PHP , integers and doubles. Integers are basicly whole numbers and doubles are fractional (floating point ) numbers . Here are some examples .

$firstint = 9;
$firstdouble = 23.67;
$secondint = - 76;
$seconddouble = -1239.7432;

The values these types can hold is platform specific but for example the range for an integer is commonly -32768 to 32767 on Windows machines.

Type Casting

As you are aware PHP automatically decides what data type but you do have the option of specifying this yourself . Here is how you can do this .

$luckynumber = 7;
$lucknumber = (string) $luckynumber;

This would give us a string rather than the integer we had previously.

Using gettype and settype functions

These are two functions provided with PHP which help us to determine the data type and set the data type respectively , lets look at examples of both . Firstly settype which will display the data type of the variable

<?php
$myname = “Iain”;
echo gettype($myname);
?>

string
Now for settype , this allows you to set the data type . The first parameter is the actual variable , the second is the data type you require) . In this example we set the data type and then use gettype to show it has changed.

<?php
$wages = 1000;
settype($wages, “string”);
echo gettype($wages);
?>

string

variables in PHP part 1

Thursday, February 21st, 2008

variables in PHP part 1
Variables

A variable is an area of memory which is set aside to store information , this is assigned an identifier by the programmer . You can recognise variables in PHP because they are prefixed with the dollar ( $ ) sign . To assign a variable you use the assignment operator ( = ) . Here is an example of this.

$name = “iain hendry”;
$intDaysInWeek = 7;

In the first example the variable identifier in this example is $name and the string value “iain hendry” has been assigned to it . In the second example the variable identifier is $intDaysInWeek and the number 7 is assigned to it . Note that in the number example we do not surround the variable with quotes in this way PHP treats this as a numeric value but if we had put quotes round it then PHP would have treated it as a string.

Variable Naming

There are some guidelines to follow for naming variables in PHP and these are as follows .
1. All variable names must begin with a letter or underscore character .
2 . The name of the variable can be made up of numbers , letters , underscores but you cant use charcters like + , - , & , £ , * , etc
One important thing to note if you are coming from another programming language there is no size limit for variables .

Case Sensitivity

One thing that causes many hours of hair pulling and anguish is case sensitivity , PHP is case sensitive (some languages are not) . Here is an example of what I mean.

<?php
$myname = “Iain Hendry”;
echo $Myname”;
?>

Now we all know what we want to do , declare a variable , assign it the value of “Iain Hendry” and then print this on the screen but in this example we have mis-spelt the variable name , when run the following error is displayed on the screen.

Warning: Undefined variable: Myname in D:\testsample.php on line 3

Example

Using your favourite HTML editor enter the following

<?php
$url = “http://www.myscripting.com”;
$rank = 1;
echo “Our favourite site is “.$url;
echo “<br>”;
echo “It is number “.$rank;
?>

here is the output you should get

Our favourite site is http://www.myscripting.com
It is number 1

Translate