regular expression with hebrew or english

牧云@^-^@ 提交于 2019-12-31 03:08:28

问题


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));
?>

回答1:


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);



回答2:


var regexp = /^[\u0591-\u05F4\s]+$/gi;
return regexp.test(str)



回答3:


How about this? Dose that work for you?

[\w\u0590-\u05FF]


来源:https://stackoverflow.com/questions/9197003/regular-expression-with-hebrew-or-english

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!