<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Webcodez - The database of web programming tutorials &#187; preg_match</title>
	<atom:link href="http://www.webcodez.net/tag/preg_match/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.webcodez.net</link>
	<description>Archive of tutorials on php,mysql,Javascript,html,css and other coding languages as well as code-snippets.</description>
	<lastBuildDate>Tue, 18 May 2010 16:43:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>User Input Validation (Part 2) Examples</title>
		<link>http://www.webcodez.net/php-mysql/user-input-validation-examples-1/</link>
		<comments>http://www.webcodez.net/php-mysql/user-input-validation-examples-1/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 10:26:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[preg_match]]></category>
		<category><![CDATA[regular expressions]]></category>
		<category><![CDATA[user input validation]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=248</guid>
		<description><![CDATA[In the previous tutorial on user input validation the basics about user input validation were explained. This tutorial will require you to have a basic knowledge about user input validations (php patterns), if you don&#8217;t know about php patterns yet I&#8217;d advice you to first have a look at the previous tutorial about user input [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://www.webcodez.net/php-mysql/user-input-validation/">previous tutorial on user input validation</a> the basics about user input validation were explained. This tutorial will require you to have a basic knowledge about user input validations (php patterns), if you don&#8217;t know about php patterns yet I&#8217;d advice you to first have a look at the previous tutorial about <a href="http://www.webcodez.net/php-mysql/user-input-validation/">user input validation</a>. In this tutorial a couple of examples of user input validation patterns will be given and explained. The patterns explained in this tutorial are for: <strong>email </strong>and <strong>website address (url)</strong> user input validations.</p>
<h2>Use of all patterns</h2>
<p>All patterns explained in this tutorial can be used by using the <strong>preg_match </strong>function, for example using an if loop:</p>
<pre name="code" class="php:nogutter">
//$value = $_POST['input_field_name']; for example
if(preg_match("/pattern/", $value))
   //matched
else
  //did not match
</pre>
<h3>Email Validation</h3>
<p>To validate a user input for an email, to check whether it&#8217;s a valid email, can be done in several ways. Here I&#8217;ll be showing 2 ways to validate an email. To create a pattern for validating an email you&#8217;ll first need to think of how an email can look like ( structure ). Which is:</p>
<blockquote><p>email_name@email_provider.lang</p></blockquote>
<p>Where &#8216;lang&#8217; can be anything like: com or net or nl ( dutch ), etc.. The &#8216;email_name&#8217; can be anything of any length containing alphabetical characters, numbers or the &#8211; _ symbols. Same goes for the &#8216;email_provider&#8217;. So for validating USA email addresses (.com) for example, we could have a pattern like this:</p>
<p><strong>Pattern:</strong></p>
<pre name="code" class="php:nogutter">
/^[A-Za-z0-9-_.]*@[A-Za-z0-9-_.]*(\.com)$/
</pre>
<p>However this pattern will only allow/match email addresses that end with .com. We could use the | seperator to allow several &#8216;extensions&#8217; for the email ( .com OR .net OR .nl, etc..). That would look like this:</p>
<p><strong>Pattern:</strong></p>
<pre name="code" class="php:nogutter">
/^[A-Za-z0-9-_.]*@[A-Za-z0-9-_.]*(\.com|\.net|\.nl|\.de|\.be|\.co\.uk)$/
</pre>
<p>And you could add all extensions you want to allow for the email address there, seperated by | and don&#8217;t forget to escape the dots (.) with a backslash (\) so it will be treated as a normal character.</p>
<p><strong>Note:</strong> a second way to do this could be to allow all extensions (.com, .net or .anythinghere). To do this just replace the \.com|\.net|etc&#8230; by <em>\.[A-Za-z0-9]*</em> which basicly means: all alphabetical characters and numbers.</p>
<p><strong>Example of use:</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php

$email = "validemail123@validprovider_09.net";

if(preg_match("/^[A-Za-z0-9-_.]*@[A-Za-z0-9-_.]*(\.com|\.net|\.nl|\.de|\.be|\.co\.uk)$/", $email)) {

    echo "&lt;p> Valid email: {$email} &lt;/p>";

}else{

    echo "&lt;p> Invalid email: {$email} &lt;/p>";

}

$email = "invalid' email@invalid,provider}.fpweo";

if(preg_match("/^[A-Za-z0-9-_.]*@[A-Za-z0-9-_.]*(\.com|\.net|\.nl|\.de|\.be|\.co\.uk)$/", $email)) {

    echo "&lt;p> Valid email: {$email} &lt;/p>";

}else{

    echo "&lt;p> Invalid email: {$email} &lt;/p>";

}

?>
</pre>
<p><strong>Output:</strong></p>
<blockquote><p>Valid Email: validemail123@validprovider_09.net</p>
<p>Invalid Email: invalid&#8217; email@invalid,provider}.fpweo</p></blockquote>
<h3>Website Address Validation</h3>
<p>For creating a pattern to validate website adresses (urls) we&#8217;ll have a look at a valid structure of a website address first, which is similar to:</p>
<blockquote><p>http(s)://(www. or subdomain.)websitename.com(/directories)(/page.ext)(?getvar&#038;getvars)</p></blockquote>
<p>Where what&#8217;s between brackets is optionally. The .com can be any other &#8216;extension&#8217; of course (.net or .co.uk, etc.).</p>
<p><strong>Pattern:</strong></p>
<pre name="code" class="php:nogutter">
/^(http)(s)?(:\/\/)(www\.|[A-Za-z0-9_-]*\.)?[A-Za-z0-9_-]*(\.com|\.net|\.co\.uk|\.net)(\/|\/[A-Za-z0-9-_ .]*)*$/
</pre>
<p>This is just an example of a pattern I created that could be used. It may at first look complex but it isn&#8217;t that complex at all if you have a further look into it. Let&#8217;s go through it briefly. Each valid website address starts with &#8216;http&#8217; (^(http)) followed by an optional &#8217;s&#8217; ( (s)? ). After that there&#8217;s a &#8216;://&#8217; which is put inside the pattern as (:\/\/) as all /s need to be escaped by a \. So // becomes \/\/. Then there&#8217;s an optional ( so a ? behind the collection  ) &#8216;www.&#8217; or &#8217;subdomain_name.&#8217; where the subdomain_name can be any alphabetical character or number or _ or &#8211; ([A-Za-z0-9_-]) and any size (* = any amount of characters). The question mark behind this collection ( www. | subdomain. ) defines it may occur one or zero times (that it&#8217;s optional). Then there&#8217;s again the [A-za-z0-9_-] which again means any alphabetical characters or numbers or the _ or &#8211; symbol, which is for the domainname of the website which may contain any of these characters in any length (*). Then it should be followed by any of these &#8216;extensions&#8217; ( \.com|\.net|\.co\.uk|\.net ). Now the rest of the pattern is optional &#8211; there can be anything after the url (after a backslash / ).</p>
<p><strong>Example of use:</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php

$url = "http://www.validurl.net/anypath/anyfile.php?anything";

if(preg_match("/^(http)(s)?(:\/\/)(www\.|[A-Za-z0-9_-]*\.)?[A-Za-z0-9_-]*(\.com|\.net|\.co\.uk|\.net)(\/|\/[A-Za-z0-9-_ .]*)*$/", $url)) {

    echo "&lt;p> Valid url: {$url} &lt;/p>";

}else{

    echo "&lt;p> Invalid url: {$url} &lt;/p>";

}

$url = "http://invalidurl-^.";

if(preg_match("/^(http)(s)?(:\/\/)(www\.|[A-Za-z0-9_-]*\.)?[A-Za-z0-9_-]*(\.com|\.net|\.co\.uk|\.net)(\/|\/[A-Za-z0-9-_ .]*)*$/", $url)) {

    echo "&lt;p> Valid Url: {$url} &lt;/p>";

}else{

    echo "&lt;p> Invalid Url: {$url} &lt;/p>";

}

?>
</pre>
<p><strong>Output:</strong></p>
<blockquote><p>Valid Url: http://www.validurl.net/anypath/anyfile.php?anything</p>
<p>Invalid Url: http://invalidurl-^.</p></blockquote>
<p><strong>Note</strong>: To only allow domain names website addresses without any paths behind it ( like: http://www.google.com ) remove the last part of the pattern between brackets followed by a * ( which is: (\/|\/[A-Za-z0-9-_ .]*)* ) or replace it by (\/)? if you do want to allow a possible ending backslash ( http://www.google.com/ ).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/user-input-validation-examples-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>User Input Validation (Part 1)</title>
		<link>http://www.webcodez.net/php-mysql/user-input-validation/</link>
		<comments>http://www.webcodez.net/php-mysql/user-input-validation/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 15:10:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[preg_match]]></category>
		<category><![CDATA[user input]]></category>
		<category><![CDATA[validation]]></category>
		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=215</guid>
		<description><![CDATA[Beside securing user input data it’s also important to validate the user input data. For example when you require the user to fill in his/her email, you do want it to be a real email address. To be more sure about this, you can use certain PHP functions to validate the user input to be [...]]]></description>
			<content:encoded><![CDATA[<p>Beside securing user input data it’s also important to validate the user input data. For example when you require the user to fill in his/her email, you do want it to be a real email address. To be more sure about this, you can use certain PHP functions to validate the user input to be a valid email address. In this tutorial we’ll be using the <strong>preg_match</strong> function to do this. The use of this function and the creation of patterns to validate user input will be explained. Actually retrieving user input from forms won&#8217;t be explained in this tutorial, only the validation process of user input using patterns and preg_match, will be explained. For retrieving the user input from forms, please take a look at the <strong>3rd part of this tutorial</strong>.</p>
<h3>Preg_match Function</h3>
<p>The preg_match function basicly checks whether a value matches the given pattern. A pattern sets the characters that the value may contain and in which order they may occur in the value and how many times. Let’s start with the preg_match function itself:</p>
<pre name="code" class="php:nogutter">
preg_match(‘/pattern/’, ‘value’);
</pre>
<p>The pattern always needs to be put between backslashes ( / &#8230; pattern here &#8230; / ). The value would be for example the user input.</p>
<h3>Using preg_match</h3>
<p>There are several ways to use the preg_match function. In this tutorial we’ll be using it to validate values ( user input ) using pattern. Therefore we’ll put the preg_match function inside an <strong>if loop</strong>. This is how it looks like:</p>
<pre name="code" class="php:nogutter">
if( preg_match(‘/pattern/’, ‘value’) ) {

//the value matched the pattern

}
</pre>
<p>This basicly just executes the preg_match function which returns TRUE when a match was found in  the value with the pattern given.</p>
<h3>Creating Patterns</h3>
<p><strong>So how do patterns look like and how do we create them?</strong> Patterns can sometimes look quite complex but usually they aren’t that complicated as they may look like. PHP uses specific symbols that can be used inside a pattern. They can be divided into 3 types: symbols that indicate the position of a character in the value, the kind of character and how many of this character the value may contain.</p>
<h3>Symbols</h3>
<p><strong>Position</strong></p>
<blockquote><p>
^(&#8230;some character &#8230;) – character (set) must be found at the beginning of the value matched<br />
$(&#8230;some character&#8230;) – character (set) must be found at the end of the value matched
</p></blockquote>
<p><strong>Characters</strong></p>
<blockquote><p>
.    – Any character<br />
[A-Za-z0-9] – All non-capital and capital alphabetical characters  and all numbers
</p></blockquote>
<p><strong>Amounts</strong><br />
These symbols are put after the character it will be working for, for example: a* or 9+</p>
<blockquote><p>
* &#8211; character may occur any amount of times<br />
+ – character may occur 1 or more times<br />
? – character may occur 0 or 1 time<br />
{1,2,3,9-11} – character may occur 1, 2, 3 or 9, 10, 11 times
</p></blockquote>
<h3>Basic Pattern</h3>
<p>Allright, now we can use any of these symbols to create our first basic pattern. Let’s create a few basic patterns and show some values that would match and some values that would not match the pattern. Let’s start creating a pattern that starts with any capital alphabetical character (A-Z) and ends with any number (0-9):</p>
<p><strong>Pattern</strong></p>
<pre name="code" class="php:nogutter">
/^[A-Z][0-9]$/
</pre>
<p><strong>Matches</strong></p>
<blockquote><p>
A9<br />
Z2<br />
R5
</p></blockquote>
<p><strong>None Matches:</strong></p>
<blockquote><p>
2V<br />
AD2<br />
F32
</p></blockquote>
<p>Allright, this pattern matches any value that starts with a capital alphabetical character and ends with a number. However it may only contain ONE of both ( as we didn’t set an amount, it means t may only occur onces ). So it must be one capital alphabetical character followed by one number.</p>
<p>Let’s edit this pattern to match a value starting with any amount of capital alphabetical characters and ending with any amount of numbers. We’ll use the * symbol to indicate that these characters and numbers sets may both occur any amount of times:</p>
<p><strong>Pattern</strong></p>
<pre name="code" class="php:nogutter">
/^[A-Z]*[0-9]*$/
</pre>
<p><strong>Matches</strong></p>
<blockquote><p>
JFL9<br />
A837<br />
S2<br />
4<br />
H
</p></blockquote>
<p><strong>None Matches:</strong></p>
<blockquote><p>
2V<br />
8O3<br />
AJK92K
</p></blockquote>
<p>Now we used the * symbol for both, to set that both (A-Z and 0-9) may occur any time. Which means 0 times is possible to. So it would as well match an empty value ( 0 times a capital character and 0 times a number )  or only 1 number or capital character. To require one of the charsets (A-Z or 0-9 for example) to occur atleast ONCE, you could use the + symbol instead of the *.</p>
<p><strong>Pattern</strong></p>
<pre name="code" class="php:nogutter">
/[A-Z][0-9]/
</pre>
<p><strong>Matches</strong></p>
<blockquote><p>
&#8216;-)A4=<br />
B9<br />
+][L3
</p></blockquote>
<p><strong>None Matches:</strong></p>
<blockquote><p>
22<br />
'[BB<br />
{}-9A
</p></blockquote>
<p>Now we took our first pattern but removed the ^ and $. So now it doesn't matter WHERE in the value string these characters were found/matched. As we didn't set an amount for each charset ( [A-Z] and [0-9] ) it matches a value of a string which has once a capital letter ( A-Z ) and once a number ( 0-9 ) and in the same order as given in the pattern ( which is: letter number, for example: A9). The rest of the string it matches can have any characters in it. For example A9 matches the pattern, but it can be in any string, like: &#8216;[-=A9&#8242;;- would match as well as it will find the A9 which matches the pattern. As we didn&#8217;t set the ^ and $ &#8211; in that case the WHOLE string should match the pattern ( from beginning ( ^ ) to end ( $ )).</p>
<h3>Using text inside patterns</h3>
<p>It&#8217;s also possible to use text inside a pattern. Like searching for the word &#8220;hello&#8221; inside a string. This would be a simple pattern:</p>
<p><strong>Pattern</strong></p>
<pre name="code" class="php:nogutter">
/(hello)/
</pre>
<p>We put the text between brackets so it will search for the word between brackets. This pattern would match for example:<br />
<strong><br />
Matches</strong></p>
<blockquote><p>hello there!<br />
are you there, hello?</p></blockquote>
<p>However if we want to find the text &#8216;hello.&#8217; (with a dot) and we create the pattern just like we did above, it won&#8217;t work the way we want it to. Because then it will see the dot as a symbol indicating any character as the dot is as well a standard symbol used for patterns in PHP. So to actually use the dot as a character, we&#8217;ll need to put a backslash before the dot so it will threat it as a character instead of a special pattern symbol.</p>
<p><strong>Pattern</strong></p>
<pre name="code" class="php:nogutter">
/(hello\.)/
</pre>
<h3>Patterns that match several specific words or strings</h3>
<p>In the previous examples above we made it match a specific word ( &#8216;hello&#8217; as above, for example ). But we can also make it match several specific words/strings. So when any of the words set was found, it will return TRUE (matched). We&#8217;ll use a new symbol to do this: |<br />
<strong><br />
Pattern</strong></p>
<pre name="code" class="php:nogutter">
/(word1|word2)/
</pre>
<p>The pattern above would match any value/string that either contains the word &#8216;word1&#8242; OR &#8216;word2&#8242;. This way you could for example match image files by checking if the extension was any of the image extensions ( JPG, GIF, PNG, etc&#8230;). </p>
<p><strong>Pattern</strong></p>
<pre name="code" class="php:nogutter">
/(JPG|JPEG|GIF|BMP|PNG)$/
</pre>
<p><strong>Matches</strong></p>
<p>All values that end with either JPG, JPEG, GIF, BMP or PNG.</p>
<h3>Conclusion</h3>
<p>Patterns can be very usefully when it comes to validating user input data and I hope you learnt something with this tutorial. It can be used to for example validate emails, website urls, image file names and much more. But don&#8217;t worry, I&#8217;ll be posting tutorials on validating these specific data values soon if not already ( like emails, urls, &#8230; )!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/user-input-validation/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
