希伯来语或英语的正则表达式 [英] regular expression with hebrew or english

查看:65
本文介绍了希伯来语或英语的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您的代码中有多个错误.

There are multiple errors in your code.

首先,你的正则表达式

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

这是什么意思:

#                     : 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 希伯来语字符是:\p{Hebrew}
在字符类中不需要 |
您的字符串中没有 +,末尾没有空格
无需进行非贪婪匹配

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

所以应该改写为:

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

说明:

#                 : 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 不返回数组而是返回一个 int在字符串中找到模式的次数.

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

然后你的脚本变成:

$subject = "שלום לך";
$regexp  = "#^[\p{Hebrew} a-zA-Z]{2,15}$#u";
preg_match($regexp, $subject, $m);
print_r($m);

这篇关于希伯来语或英语的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆