Forum Moderators: coopster

Message Too Old, No Replies

Preg match help

         

BlackRaven

9:35 pm on Apr 10, 2007 (gmt 0)

10+ Year Member



Trying to use preg_match to match the following form http://www.example.com/user-45...what am i doing wrong?

preg_match("/^http[:\/\/]+[www]+\.[a-z0-9\-_]+\.[a-z.]{2,6}+[\/a-z0-9\-_]$/i",$_POST['url'])

joelgreen

11:26 pm on Apr 10, 2007 (gmt 0)

10+ Year Member



You could try something like this. Did not test it though
preg_match("/http:\/\/www\.[a-z0-9-_]+\.\/[a-z.]{2,6}+\/[a-z0-9\/-_]/i",$_POST['url'])

Drunk N Japan

4:11 pm on Apr 11, 2007 (gmt 0)

10+ Year Member



I am having a similar problem. I am trying to check a street address to make sure there are numbers, letters, periods, and spaces. I know how to write the preg_match to check for the first 3 items, but I cannot figure out how to write it to check for all four. I want to make sure the address is entered like 123 Main St. not 123MainSt. I have read many posts on this subject for checking email addresses but I haven't seen one about street addresses. Appreciate the help.

borntobeweb

5:07 pm on Apr 11, 2007 (gmt 0)

10+ Year Member



This will check that some portion of the address matches "123 Main St"

preg_match('/\b(\d+)\s+(\w+)\s+(\w+)\b/', trim($input_value))

But to do a complete test you'll need a lot more to take into account street names with multiple words (123 Important Person Pkwy), different street types, street direction (123 1st Ave West), street number suffixes (123A Main St), and apt numbers, something like (without apt numbers):

preg_match(
'{\b\d+([A-Z]¦\d/\d)?\s+(\w+\s+)+\w+\.(\s+([nesw]¦[ns][ew]))?\b}i',
trim($input_value))

breaking it down:
\b is word boundry
\d+([A-Z]¦\d/\d)? matches street number with an optional letter suffix or 1/2,1/4,etc suffix
(\w+\s+)+ matches one or more words for the street name
\w+\. matches the street type
(\s+([nesw]¦[ns][ew]))* matches an optional street direction (n,s,e,w,ne,se,nw,sw)

This is from Canadian addresses, other countries might have different conventions.

BlackRaven

5:51 pm on Apr 11, 2007 (gmt 0)

10+ Year Member



i tried
preg_match("/http:\/\/www\.[a-z0-9-_]+\.\/[a-z.]{2,6}+\/[a-z0-9\/-_]/i",$_POST['url'])

however that doesnt seem to work...:(

borntobeweb

8:18 pm on Apr 11, 2007 (gmt 0)

10+ Year Member



Hi BlackRaven, try this:

preg_match("{http://www\.[a-z0-9-_]+(\.[a-z]+){1,2}/[a-z0-9/-_]}i", trim($_POST['url']))

this will match http://www.example.com/user-24 and also http://www.example.co.uk/user-24 etc, add a ^ and $ to the beginning and end of the pattern to validate the entire string.

You might also want to look into parse_url: [php.net...] e.g.


$url_parts = @parse_url(trim($_POST['url']));
if($url_parts === false)
echo 'bad url';
else if($url_parts['scheme']!= 'http')
echo 'only http allowed';
...