-1

I have no. of strings and i want to identify those string which have special characters.

I am trying this to do above

if (!preg_match('/[^A-Za-z0-9]/', $url)) {
    echo "special character";
}

And I have also tried:

if (ctype_alnum($url)) {
    echo "special character";
}

The character i want to allow are a-z, A-Z, 0-9,_,-,/

And my string containing special character is like

torbjörn-hallber etc.

how can i do that ? please help.

pavel
  • 26,538
  • 10
  • 45
  • 61
afeef
  • 547
  • 3
  • 9
  • 25
  • possible duplicate of [PHP: How to tell if a string contains any special characters?](http://stackoverflow.com/questions/3256175/php-how-to-tell-if-a-string-contains-any-special-characters) – Saty May 12 '15 at 11:51

1 Answers1

3

Your first attempt with preg_match was good, just don't negate the return value.

if (preg_match('/[^A-Za-z0-9]/', $url)) {
    echo 'special character';
}

You want to allow more characters including /, so I use ~ as a delimiter.

if (preg_match('~[^a-z0-9/_-]~i', $url)) {
    echo 'special character';
}
pavel
  • 26,538
  • 10
  • 45
  • 61
  • [panther](http://stackoverflow.com/users/1595669/panther) I tried but its giving me a string - macvittie as it have special character and torbjörn-hallber as a valid string inside if block. – afeef May 12 '15 at 11:53
  • @afeef: impossible, are you sure you removed `!` before `preg_match`? Both regex works. – pavel May 12 '15 at 11:55
  • panther got it now. but how to add more char in it ? bcoz when i do this (preg_match('~[^a-z0-9/_-.]~i', $url)) (added . as extra char ) it gives me a error Compilation failed: range out of order in character class at offset 11 – afeef May 12 '15 at 12:01
  • @afeef: dash has to be at the end, else the PHP try to use it as range between `_` and `.`. Use `~[^a-z0-9/_.-]~i`. – pavel May 12 '15 at 12:05