3

I'm looking for a pattern that accept only hebrew or english letters from 2 letters to 15, and can accept 1 space. I have tried following code but it does not matching my string:

<?php
$subject = "שלום לך";
$regexp="#^\p[{Hebrew}| ][a-zA-Z]{2,15}? \+$#u";
print_r(preg_match($regexp, $subject));
?>
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
ofir
  • 129
  • 1
  • 4
  • 12
  • Note - similar regular expression can be used in other dialects of regular expression, i.e. for C#/.Net is [IsHebrew](http://msdn.microsoft.com/en-us/library/20bw873z(v=vs.110).aspx#SupportedUnicodeGeneralCategories) instead. – Alexei Levenkov Sep 26 '14 at 14:58

3 Answers3

6

There are multiple errors in your code.

First, your regex

$regexp="#^\p[{Hebrew}| ][a-zA-Z]{2,15}? \+$#u";

Here is what it means:

#                     : regex delimiter
  ^                   : begining of string
    \p                : character p
    [{Hebrew}| ]      : character class, one of the char : {, H, e, b, r, w, }, |, space 
    [a-zA-Z]{2,15}?   : from 2 to 15 alphabetic char
     \+               : a space followed by +
  $                   : end of string
#                     : regex delimiter
u                     : unicode

Unicode hebrew char is : \p{Hebrew}
there no needs of | inside a char class
there is no + in your string, no space at the end
there no need to do ungreedy matching

so it sould be rewritten as:

$regexp="#^[\p{Hebrew} a-zA-Z]{2,15}$#u";

explanation:

#                 : regex delimiter
  ^               : begining of string
    [             : start class character
      \p{Hebrew}  : a hebrew character
                  : a space
      a-zA-Z      : a latin letter
    ]             : end of class
    {2,15}        : previous chars 2 to 15 times
  $               : end of string
#                 : regex delimiter
u                 : unicode

preg_match doesn't return an array but an int that holds the number of time the pattern is found in the string.

Then your script becomes:

$subject = "שלום לך";
$regexp  = "#^[\p{Hebrew} a-zA-Z]{2,15}$#u";
preg_match($regexp, $subject, $m);
print_r($m);
Toto
  • 89,455
  • 62
  • 89
  • 125
1
var regexp = /^[\u0591-\u05F4\s]+$/gi;
return regexp.test(str)
gunr2171
  • 16,104
  • 25
  • 61
  • 88
eliprodigy
  • 600
  • 6
  • 8
1

How about this? Dose that work for you?

[\w\u0590-\u05FF]
Community
  • 1
  • 1
Mbrevda
  • 2,888
  • 2
  • 27
  • 35