preg_match doent seem to work

Hello,

I want to validate a string like:
“v=spf1 a -all”
but it should also b possible to fill in a numeric value or something lik mail.website.com. It’s used for a dns manage tool.

If have tested the following:

if(!preg_match(“[1]^”, $_GET[‘data’])) {

For some reason this doenst seem to work. I think i am doing something wrong with the delimiters but i dont see what i have to change to let this work.

Any suggestions?

Regards,

Weccop


  1. 0-9a-z .\-\=\" ↩︎

The colon character (:) is being matched by the regex so preg_match returns 1.

The system still fails on the following string:

v=spf1 mx ip4:194.109.125.128/27 -all

I have added the : and tried this version:

<?php
if (preg_match(‘~[^a-z0-9"\s.=/-]~’, $subject) {
// echo 'Invalid! ’ . $subject;
}
?>

That’s because when starting with a character, regex is only valid until that character next appears undelimited. That’s why I recommend using ~ rather than / :

if (preg_match('~[^a-z0-9"\\s.=/-]~', $subject) {
    // echo 'Invalid! ' . $subject;
} 

preg_match will return 1 if the pattern matches the subject string or 0 if that pattern did not match (or false if there’s a problem). Since you want to make sure that the string only contains characters in that specific list there are a few approaches.

  1. Check that the whole string contains only the letters that you want

    php if (preg_match('/^[a-z0-9".=-]*$/Di', $subject) { // echo 'Invalid! ' . $subject; }
  2. Check if any one character is not within the allowed list

    php if (preg_match('/[^a-z0-9".=-]/i', $subject) { // echo 'Invalid! ' . $subject; }

Note: both of these will allow an empty string (“”); you didn’t say whether that should be allowed or not. If you let us know which approach you like best (it doesn’t have to be one of the above) then we can help explain it in detail if you’re not really sure what is going on.

I won’t appear in that string.

It could be a input from a user like:
mail
192.168.0.1
“v=spf1 a -all”
mail.website.com

Looks great i have googled a litle bit on the /^and the /i and I understand what its doing now. I have used the second version and added a space else he wouldn’t validate it.

What would i have to change to only allow a / in the check. I have tried some version but i receive errors when i add the / or a //.

Do you have a sample of the string you would like to match, you’re being awfully vague I’m afraid.

Pop a few samples up and we’ll see what we can do.

:wink:

…where would ‘mail’ or the IP address appear in the string you provided?

The string i want to validate is:
“v=spf1 a -all” (quotes included)

But it must also allow something like the word mail or a ip adress. So it should check if there arent any othe characters in the string the things like a-z0-9 and " = - .