-2

i need to check text in php and allow only english

my code is:

Should match:

Gautier-, !@#$%^&*()_+|';?>< A.; R.; Falcs, J.M;

Should not match:

Problem dojrzałościmałżeństwa"; // not allowed
book for محمد taj
Еос ферри

Code :

if (! preg_match('/^[a-z0-9 .\-]+$/i',  $string) ) 
{
  echo "Not allowed";
}

But not work

Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
Admin File3
  • 119
  • 10
  • 2
    What does “allowing only English” have to do with limiting the set of possible characters? That approach is rather naïve (perfectly valid English word), or as we would perhaps say in German, “dumm wie Brot” - now what characters would you want to limit to exclude _that_ …? – CBroe Mar 27 '17 at 11:31
  • Polish word "tlen" (and many others) only comprises ASCII letters, no regex will tell you it is not English. It is a task for NLP, language guessing algorithms. To only check if a string only consists of ASCII chars, use `^[[:ascii:]]+$`. – Wiktor Stribiżew Mar 27 '17 at 12:01
  • See http://stackoverflow.com/questions/24903140/regex-for-any-english-ascii-character-including-special-characters – Wiktor Stribiżew Mar 27 '17 at 12:48
  • it worked ! very thanks ... @WiktorStribiżew – Admin File3 Mar 27 '17 at 21:31
  • `if (! preg_match('%^[ -~]+$%', $string) ) { echo "Not allowed"; }` it worked ! – Admin File3 Mar 27 '17 at 21:33

2 Answers2

1

Use this :

if (!preg_match('/^[a-z0-9 .}, !@#$%^&*()_+|\';?><-]+$/i', $string)) 
{
  // commands
}
tasosxak
  • 109
  • 10
1

Just add the special characters in the character class:

if (! preg_match('/^[a-z0-9 .}, !@#$%^&*()_+|\';?><-]+$/i',  $string) ) {
  echo "Not allowed";
}
Toto
  • 89,455
  • 62
  • 89
  • 125
  • I need to filter non english words not chars, who can help with this please? I wish to use php and text file and a list of words most are english some are not and don't belong whats easyest way in php to strip them non engllish words out? capitals or lack of dont matter just the words! – Jay Mee Feb 24 '20 at 02:19