Showing posts with label PHP Regular Expression. Show all posts
Showing posts with label PHP Regular Expression. Show all posts

30 December, 2010

Basic url rewrite example

URL that is readable looks nice. But despite efforts by developers, sometimes for instance, using a Content Management System (CMS) serve url's in the format like,

http://www.testthis.com/list_products?cat_name=Shirts&cat_id=8


Now, this is really a bad url, and is prevelant with dynamic pages. Some of the problems of such url's are:
1) It exposes the type of data, query string to malicious users.
2) The characters such as question mark and ampersand can be troublesome.
3) Such url's wont be indedxed by search engines.

Solution to this is, above url can be mapped to something like this;

http://www.testthis.com/products/Shirts/8


Looks much better. And in order to do such mapping, we need url rewriting.
Apache's mod_rewrite gives us the ability to rewrite urls. Url rewrite can be
done to redirect from old to new address, clean up dirty url's, as mentioned above.
This makes our url's search engine friendly which means search engines can index such urls.

For url rewrite, we create a file .htaccess at the root of our project, and add following line.

RewriteEngine On


Basic Redirects

Lets say we moved all of our files from an older location to a new one, now we want to redirect all the links to current location. For that we can do the following.

RewriteEngine On
RewriteRule ^old\.html$ new.html


What the above rule does, is, it simple redirect from old.html to new.html page.
The ^ sign indicates Start of the url to be matched. If this character is removed, then our rule would also match hold.html
The $ sign indicates end of the string to be matched. In this case users would not know a redirect has occured from old.html to new.html

But lets say you want users to know that redirect has occured, that means you want to force a redirect. In such case you can do as,

RewriteEngine On
RewriteRule ^old\.html$ new.html [R]


Using Regular Expressions in Url Rewrite
The full strength of mod_rewrite can be felt at expense of complexity. Using regular expressions for url rewrite, you can have rules for set or urls, and have redirection for all to actual pages.
For example,

http://www.testthis.com/list_book?bookId=20


Now, we can rewrite this kind or url to make it friendly, as,

RewriteEngine On
RewriteRule ^book/([0-9][0-9])/$ list_book.php?bookId=$1


So above rule will create urls such as, http://www.testthis.com/book/8

But if a user types in like, http://www.testthis.com/book/8, our url rewrite rule wont work, as the slash at the end is missing, so to prevent such problems, we can do as,

RewriteEngine On
RewriteRule ^book/([0-9][0-9])/$ book/$1/ [R]
RewriteRule ^book/([0-9][0-9])/$ list_book.php?bookId=$1


Now, if a user enters something like book/12, our first rules comes in to add a slash at the end,then second
rule comes into play.

Regular expressions in url rewrite can be expanded by using modifiers, that allow you to match url with indefinite number of characters. Lets say, our url is like,
http://www.testthis.com/list_book?bookId=220

Our rule wont match this, as we have checked against two digits only, so we should use modifiers in this case.

RewriteEngine On
RewriteRule ^book/([0-9]+)$ book/$1/ [R]

+ indicates one or more of the preceeding characters or range.
* means 0 or more preceeding characters or range

So, above rule will match both book/1 and book/3000

In this way we can use mod_rewrite to rewrite url. These are just an introductory examples. There's a lot more way to move ahead in url rewriting and regular expressions. I hope this basic url rewrite post can be of some help to others.

10 November, 2010

Regular expression examples in php

Regular expressions in php are a good way for validating against user inputs. Though
usage of regular expressions slow the execution, and are really slower as compared to
string functions, they can be quite fun to play with if known how to. Regex can be used in different programming languages but since i work with PHP, i use them using PHP.

At the beginning, regex seemed to be invincible to me, but as i got into details of
its usage and worked with test codes, i got more and more interested.
So here are some of the common validation examples that can be done using regular expressions in php.
Following mentioned are code for 5 simple regular expression examples for validation in php.

1: Regular expression to check for integer value excluding 0

$test = "123";
$result = 0;

$pattern = "(^([1-9]{1})(([0-9]{1,10}))?)$";
$result = (int) ereg($pattern, $test);
echo $result;

2: Regular expression to check for integer value including 0

$test = "1230";
$result = 0;
$pattern = "(^([0-9]{1})(([0-9]{1,10}))?)$";
$result = (int) ereg($pattern, $test);
echo $result;

3: Regular expression to check for integer value double or float, such as 1.23, 0.48, , 0.487 etc

$test = "123.23";
$result = 0;
$pattern = "^(([0-9]{1,9})(\\.)?)(([0-9]{0,1})([0-9]{0,1})(([0-9]{0,1})([0-9]{0,1})?))$";
$result = (int) ereg($pattern, $test);
echo $result;

4: Regular expression to check for string between 1 to 255 characters, no spaces
 
$test = "thisisatest";
$result = 0;
$pattern = "^([[:alnum:]]){1,255}$";
$result = ( ereg($pattern, $test);
echo $result;

5: Regular expression to check for valid email address
 
$test = "this@gmail.com";
$result = 0;
$pattern = '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+' . '@' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$';
$result = (int) ereg($pattern, $test);
echo $result;

Above mentioned are just few examples that i have mentioned in this post. There is a long way to go with regular expressions in php. I hope this post provide at least some info regarding usage of regular expressions with php.

27 September, 2010

How to remove non-ascii characters from string

There is a simple way to remove non-ascii characters from a string. This can be used to filter values from POST variables as well. Following line of code does the thing.

$string = "This is a test É";
//replace the non-ascii characters from string with nothing i.e. remove
preg_replace('/[^(\x20-\x7F]*/','',$string);
echo $string;

23 September, 2010

Regular Expressions using Javascript

Sometimes regular expressions can be confusing, but they are great tools for matching a string against a character pattern. They are used for validation of user entry or changing the document content. You can replace a 40 line if/else code with just one line of regular expression. For starters, regular expressions can be fear striking but as you move on with the flow its keeps of getting more and more interesting.
Different languages support regular expressions and they are not as tough as they seem at first sight. Many languages support "find" ,"replace" and "search" feature in regular expressions.
So in this article i will be writing about regular expressions using javascript, to the point that I am also informed to.
Basic Syntax
Let's say you want to search for a string "rain" in a text. You can use two different formats for this.
First is using String Notation


var srchFor = /rain/; //do not use quotation marks
//Second is Object Constructor
var srchFor = new RegExp('rain');
//You can check this as follows:
var str = "When will it rain";
alert(srchFor.test(str));


The expression can be checked using match(), test(), search() or exec() method, all of these are listed later.
Let's say now you want to match a word that starts with some string, in this case, 'rain', you can check this by:


var srchFor = /^rain/;
var srchFor = new RegExp('^rain');
//Or you want to match a word that has just some string and en, in this case, has only 'rain' in it:
var srchFor = /^rain$/;
var srchFor = new RegExp('^rain$');


Here, ^ and $ are starting and ending indicator respectively.
And if want to match a word that ends with some string, in this case 'rain', then


var srchFor = /rain$/;
//Case sensitivity can also be checked. Like,
//if you want to find a word that ends with 'rain' regardless of the case,
//then:
var srchFor = /rain$/i; //Here i refers to case-insensitive
var srchFor = new RegExp('rain$', 'i');


Lets, say we have string that have the word 'rain' several times, now if we want to match a word that is repeated several times, then we can add a global
parameter 'g', doing this will return the matches as array. Such as:

var srchFor = /rain/g; //g refers to global


By default regular expressions match patterns only in single-line strings, so if we want to have a match for multiline strings using regular expressions then 'm' can be used. Such as,

var srchFor = /rain/m; //This matches for rain in multiline

And the parameters can be used in conjunction as well, like,

var srchFor = /rain/igm; OR /rain/gim OR /rain/min; etc in any order

So the above pattern matches 'rain' in multiline,regardless of case and returns array.

Period Character (.)
The dot character means match anything. Such as, match a string that has r at beginning and n at end. Such as,

var srchFor = /r.n/;

The above pattern matches 'ran', 'rin', 'ron', or even r#n or r n, etc.
However you can limt your choices by using square brackets, like

var srchFor = /r[au]n/;

The above pattern matches 'ran' or 'run'.
Exclude you choice, such as match a string excluding some , such as if you want to exclude 'ran' from searcgh then, do the following,

var srchFor = /r[^a]n/;
//But the square brackets match only one character at a time,
//so if you want to match multiple characters then pipes can be used,
var srchFor = /r(^a|u|i|eig|e)/;

This matches 'run', 'rin', 'reigh' and 'ren' but does not match 'ran'.

Escaping Characters
Certain characters need to be escaped, such as: +, /, -, (, ), *, {, }, and ?
Such as /r.n/ matches ran, run, but /r\.n/ only matches "r.n".
Lets us say, you want to validate email address using regular expression, then do the following:


var srchFor = /^[\W]+(\.[\W]+)*@([\W]+\.)+[a-z]{2,7}$/i;


In above case,
\W is shortcut for [^a-zA-Z0-9_]; match characters that have a to Z characters or 0 to 9 and underscore.
+ means 1 or more times possible
* means 0 or more times possible
? means 0 or 1 times possible
{n} means n times possible
{n,m} means n to m times possible
So,

var srchFor = /^[\W]+(\.[\W]+)*@([\W]+\.)+[a-z]{2,7}$/i;

/^[\W]+(\.[\W]+)* matches sudhi, or sudhi.test
then add @ symbol, then
([\W]+\.) matches oncemore, oncemore.co
then add dot (.),
[a-z]{2,7} means 2 to 7 times the a-z characters are possible.
Other shortcuts are
\d means [0-9] Only integers
\D means [^0-9] All characters but integers
\w means [a-zA-Z0-9_] All alphanumeric characters and the underscore
\W means [^a-zA-Z0-9_] All nonalphanumeric characters
\b means N/A Word boundary
\B means N/A Not word boundary
\s means [\t\n\r\f\v] All whitespace
\S means [^\t\n\r\f\v] No whitespace

Methods Using Regular Expressions
There are several methods that take regular expressions as parameters. The expression itself—
the things inside the slashes or the RegExp constructor—is called a pattern, as it matches what
you want to retrieve or test for.
• pattern.test(string): Returns true or false depending on whether it matches the string
• pattern.exec(string): Returns array on finding match
• string.match(pattern): Returns array of strings on finding match
• string.search(pattern): Matches the string and the pattern and returns the positions and returns -1 if not found
• string.replace(pattern, replaceString): Matches the string against the pattern and replaces every positive match with replaceString.
• string.split(pattern, limit): Matches the string against the pattern and splits it into array



So, Regular expressions only match characters; you cannot do calculations with them. And they are language independent.

12 November, 2009

Time format check regular expression

Following regular expression checks for time correctness:

(1[012]|[1-9]):[0-5][0-9] (am|pm)