tags:

views:

62

answers:

4

I need to use preg_match to check that only a-z0-9. is used (including full stop(.)). I don't want to replace anything. My problem is that it doesn't notice white space at beginning of a string.

Also, if anyone knows how to check there is no two full stops in a row, I would be very grateful.

What I have so far:

("/[^a-z0-9.]+$/",$request)

Thanks !

+3  A: 

You can do this without regex using ltrim'

if(ltrim($request) != $request) { // there was whitespace }

adam
I don't want to replace anything.
ITg
@ITg - you're not replacing anything here - just checking to see if there was whitespace at the beginning.
thetaiko
He wants to check whether there are no other chars than .a-z0-9 not if there is no whitespace at the beginning.
Kamil Szot
if((!preg_match("/^(?!.*\.{2,}.*$)[a-z0-9.]+$/",$request)) }Works how I want it to.
ITg
I gave correct answer to person with lowest 'points?' out of the two contributing answers :) Thankyou !
ITg
A: 
("/[^a-z0-9.]/",$request)

Edit - I misread your question. This will check to see if there are any non a-z0-9. characters.

thetaiko
Doesn't seem to work :/
ITg
^ inside [] is wrong
Kamil Szot
A: 

^ inside [] negates characers (changes meaning to "any char except these")

^ outside of [] means "beggining of the string" (same as $ means "end of the string")

So you need something like that:

("/^[a-z0-9.]+$/",$request)

If you want to exclude sequences of dots but not single dots you need something bit more complicated:

preg_match('/^([a-z0-9]|(?<!\\.)\\.)+$/', $request);

Kamil Szot
+1  A: 
/^(?!.*\.{2,}.*$)[a-z0-9.]+$/

Explanation

^          # start-of-string anchor
(?!        # begin negative look-ahead ("a position not followed by...")
  .*       # anything
  \.{2,}   # a dot, two times or more
  .*       # anything
  $        # the end of the string
)          # end negative lookahead
[a-z0-9.]+ # a-z or 0-9 or dot, multiple times
$          # end-of-string anchor

matches

  • "abc"
  • "abc123"
  • "abc.123"

fails

  • " abc"
  • "abc..123"
  • "abc!"
Tomalak
if((!preg_match("/^(?!.*\.{2,}.*$)[a-z0-9.]+$/",$request)) }Works how I want it to
ITg
I gave correct answer to person with lowest 'points?' out of the two contributing answers :) Thankyou though !
ITg
@ITg: you gave "correct answer" to somebody who did not answer your question. My answer checks if there are no two full stops in a row, the other one does not.
Tomalak
I tried something like m..mm but it did not validate.
ITg
Problem Solved :)
ITg
But he validated the white space at the beginning. Stop being greedy :P
ITg
@ITg: It does not validate `m..mm` because you said so in your question: *"if anyone knows how to check there is no two full stops in a row"*. And it does not validate whitespace, at least not for me - I'm not sure what you are doing, though.
Tomalak