简体   繁体   English

使用 PHP 正则表达式在字符集中至少出现两次或多次

[英]Two or more occurrence of at least one in character set with PHP regex

I want to make PHP regex to find if text has two or more of at least one character in character set {-, l, s, i, a}.我想制作 PHP 正则表达式来查找文本是否在字符集 {-, l, s, i, a} 中有两个或多个至少一个字符。 I made like this.我是这样做的。

preg_match("/[-lisa]{2,}/", $text);

But this doesn't work.但这不起作用。 Please help me.请帮我。

Matching two or more occurrences means matching two is enough for the check to be valid.匹配两个或多个匹配项意味着匹配两个就足以使检查有效。

At least one in character set might either mean you want to match the same char from the set or any of the chars in the set two times.字符集中至少有一个可能意味着您想要匹配集中的相同字符或匹配集中的任何字符两次。 If you want the former, when the same char repeats, you can use preg_match('~([-lisa]).*?\1~', $string, $match) ( note the single quotes delimiting the string literal, if you use double quotes, the backreference must have double backslash), if the latter, ie you want to match ..l...i.. , you can use preg_match('~[-lisa].*?[-lisa]~', $string, $match) or preg_match('~([-lisa]).*?(?1)~', $string, $match) (where (?1) is a regex subroutine that repeats the corresponding group pattern).如果你想要前者,当相同的字符重复时,你可以使用preg_match('~([-lisa]).*?\1~', $string, $match)注意分隔字符串文字的单引号,如果你使用双引号,反向引用必须有双反斜杠),如果是后者,即你想匹配..l...i.. ,你可以使用preg_match('~[-lisa].*?[-lisa]~', $string, $match)preg_match('~([-lisa]).*?(?1)~', $string, $match) (其中(?1)是一个正则表达式子例程,它重复相应的组模式)。

If your strings contain line breaks, do not forget to add s modifier, preg_match('~([-lisa]).*?\1~s', $string, $match) .如果您的字符串包含换行符,请不要忘记添加s修饰符preg_match('~([-lisa]).*?\1~s', $string, $match)

More than that, if you want to check for consecutive character repetition , you should remove .* from the above patterns, ie 1) must be preg_match('~([-lisa])\1~', $string, $match) and 2) must be preg_match('~[-lisa]{2}~', $string, $match) (though, this is not what you want judging by your own feeback, so this example here is just for the record).不仅如此,如果要检查连续字符重复,则应从上述模式中删除.* ,即 1) 必须是preg_match('~([-lisa])\1~', $string, $match)和 2) 必须是preg_match('~[-lisa]{2}~', $string, $match) (虽然,这不是你想要的,根据你自己的反馈来判断,所以这里的这个例子只是为了记录) .

The ([-lisa])\1{2} pattern that you find useful matches a repeated - , l , i , s or a char three times ( --- , lll , sss , etc.), thus only use it if it fits your requirements.您发现有用的([-lisa])\1{2}模式与重复a -lis或 char 匹配三次( ---lllsss等),因此仅在以下情况下使用它它符合您的要求。

Note that preg_match functions searches for a match anywhere inside a string and does not require a full string match (thus, no need adding .* (or ^.* , .*$ ) at the start and end of the pattern).请注意, preg_match函数在字符串中的任何位置搜索匹配,并且不需要完整的字符串匹配(因此,无需在模式的开头和结尾添加.* (或^.*.*$ ))。

See a sample regex demo , feel free to test your strings in this environment.查看示例正则表达式演示,随时在此环境中测试您的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM