Help with regular expression.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
GregArtemides
Forum Newbie
Posts: 5
Joined: Fri Jun 13, 2003 7:03 pm

Help with regular expression.

Post by GregArtemides »

if (!ereg("([0-9]{9})\(xml)|(txt))","123457890.txt")) echo "error!";

What's wrong with this regular expression? I need one that will check a filename has 9 numeric digits and a .txt or .xml extension.
The one above should echo the error since it's 10 digits long before the dot, but it doesn't work.
Where did I go wrong? 8O
User avatar
Wayne
Forum Contributor
Posts: 339
Joined: Wed Jun 05, 2002 10:59 am

Post by Wayne »

Code: Select all

if (!ereg("^(ї0-9]{9})\.((xml)|(txt))","1234567890.txt")) echo "error!";
- 123457890.txt is 9 characters long
- if you dont tell it to check from the beginning of the filename it doesnt care where the 9 characters start so wether it has 9 or 12 characters it will still match the 9 you told it to.

hope that helps, good luck.
m3rajk
DevNet Resident
Posts: 1191
Joined: Mon Jun 02, 2003 3:37 pm

Post by m3rajk »

there was also no check for \. in the code he posted.

not to mention eregi is posix, it's slightly slowr than perl. and i think someone said it's been deprecated.. i also know that perl has non-greedy abilities, posix doesn't.

try it in perl:
preg_match('/^\d{9}\.((xml)|(txt))/i', $file_name);

if you notice, at the end i have the letter i, this makes it case insensitive. that means not only will xml match xml, bus so will Xml, xMl, xmL, XMl, XmL, xML, XML


i also used a perl short. \d is the same as [0123456789]
Post Reply