Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP : Preg_match not work when have "/"

This one is killing me:

echo preg_match("/([a-zA-Z0-9\-\.]+)\.([a-zA-Z0-9]+)/",'downcom');

This one print 0 , because it wrong.

echo preg_match("/([a-zA-Z0-9\-\.]+)\.([a-zA-Z0-9]+)/",'down.com');

This one print 1 , its right.

My question is: why this one still print 1.

echo preg_match("/([a-zA-Z0-9\-\.]+)\.([a-zA-Z0-9]+)/",'down.c/om');

I want my preg_match check domain , domain.com only. I don't want people enter domain.com/asda , but it still allow people enter / even I don't set / in [a-zA-Z0-9-.]+

Thanks your help.


2 Answers

Looks like you just need to add the beginning and end boundaries ^, $:

echo preg_match("/^([a-zA-Z0-9\-\.]+)\.([a-zA-Z0-9]+)$/",'down.c/om');
//---------------^^^--------------------------------^^^
// Prints 0

The reason yours failed was that the pattern did in fact match the string down.c, but since you didn't include the $ end of string, any additional characters did not need to match the regex pattern so /om could be ignored. By including $, you force the test string to be matched up to its end.

like image 180
Michael Berkowski Avatar answered Jan 29 '26 09:01

Michael Berkowski


Let's break down your regular expression to see what it's doing:

([a-zA-Z0-9\-\.]+)

This first part is saying 1 or more of these characters, which matches "down" just fine.

\.

Then we match a single dot.

([a-zA-Z0-9]+)

Then we match 1 or more of these characters. The 'c' fulfilled the 1 or more rule, so it returns true. If you want to match exactly three characters, change your regular expression to something like:

echo preg_match("/([a-zA-Z0-9\-\.]+)\.([a-zA-Z0-9]{3})/",'down.c/om');

That should return false, as you expect. Michael's positional anchor tip (from his answer) is also useful, though you'll want to make sure what comes in has been trimmed ($ can match against \n, as I found out yesterday). You could also use the D modifier or the \z assertion to make sure you're at the end of the line. Here's how it might look when put together:

echo preg_match("/^([a-zA-Z0-9\-\.]+)\.([a-zA-Z0-9]{3})$/D",'down.c/om');
like image 25
Jonah Bishop Avatar answered Jan 29 '26 08:01

Jonah Bishop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!