正则表达与希伯来语或英语

ofi*_*fir 2 php regex hebrew preg-match

我正在寻找一种只接受2个字母到15个字母的希伯来语或英文字母的模式,并且可以接受1个空格.我尝试过以下代码,但它与我的字符串不匹配:

<?php
$subject = "???? ??";
$regexp="#^\p[{Hebrew}| ][a-zA-Z]{2,15}? \+$#u";
print_r(preg_match($regexp, $subject));
?>
Run Code Online (Sandbox Code Playgroud)

Tot*_*oto 5

您的代码中存在多个错误.

首先,你的正则表达式

$regexp="#^\p[{Hebrew}| ][a-zA-Z]{2,15}? \+$#u";
Run Code Online (Sandbox Code Playgroud)

这意味着什么:

#                     : 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
Run Code Online (Sandbox Code Playgroud)

Unicode希伯来字符是:\p{Hebrew}
没有需要|在一个char类
里面没有+你的字符串,没有空格到底
有没有必要做不合适的匹配

所以它可以改写为:

$regexp="#^[\p{Hebrew} a-zA-Z]{2,15}$#u";
Run Code Online (Sandbox Code Playgroud)

说明:

#                 : 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
Run Code Online (Sandbox Code Playgroud)

preg_match不返回数组,而是返回一个int,它保存在字符串中找到模式的时间.

然后你的脚本变成:

$subject = "???? ??";
$regexp  = "#^[\p{Hebrew} a-zA-Z]{2,15}$#u";
preg_match($regexp, $subject, $m);
print_r($m);
Run Code Online (Sandbox Code Playgroud)