7

I am using pspell to spell check some words. However if the word is something like G3523B it clearly is not a misspelled word but pspell changes it to GB. I would like somehow to qualify a word as a word before trying to spell check it. Maybe checking to see if the string contains any numbers or special characters.

So what is the best way to check a string for special chars or digits?

(if someone has a better idea to achieve what I am after please share)

JD Isaacks
  • 56,088
  • 93
  • 276
  • 422
  • maybe something like if($str == htmlspecialchars($str, ENT_NOQUOTES)) echo 'no special chars' or use some regexp. Obviously both solutions will slow down the application. – Narcis Radu Jul 15 '10 at 13:58

2 Answers2

11

How about using a regex:

if (preg_match('/[^a-zA-Z]+/', $your_string, $matches))
{
  echo 'Oops some number or symbol encountered !!';
}
else
{
  // Everything fine... carry on
}
IMSoP
  • 89,526
  • 13
  • 117
  • 169
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • You beat me to a similar solution: `$is_word = (preg_match('/[^a-z]/i', $string) == 0)`; – Mike Jul 15 '10 at 13:59
  • Thanks, I think I should also include `'` for words like don't... so should I also include the `\` in my character class since I am using mysql_real_escape_string? Thanks! – JD Isaacks Jul 15 '10 at 14:00
  • 1
    @John Isaacks: I think that is not needed, we are checking anything that is not alphabet, so it will also be rejected. – Sarfraz Jul 15 '10 at 14:06
  • 1
    @John Isaacks: If you want to allow apostrophes (or anything else) to be allowed through for spell checking, then yes, you do need to include it in the list of allowed characters. For example, to allow letters and apostrophes: `$is_word = (preg_match('/[^a-z']/i', $string) == 0);` – Mike Jul 15 '10 at 14:14
6

If you just want to check whether the string $input consists only of characters a-z and A-Z you can use the following:

if(!preg_match('/^\[a-zA-Z]+$/',$input)) {
   // String contains not allowed characters ...
}
Javaguru
  • 890
  • 5
  • 10