[英]Regular expression for limiting character not working
I want to limit the number of "b" between 1 and 6, for which I'm using the following code: 我想将“ b”的数量限制在1到6之间,为此我使用了以下代码:
<?php
$str="Big black books being kept in a black bag of a beautiful babe";
$pattern="/(b){1,6}/";
if(!preg_match($pattern,$str,$matches))
{
echo "Please use six bs";
}else
{/*do nothing*/}
print_r($matches);
?>
But It's not working. 但这不起作用。 What am I doing wrong? 我究竟做错了什么?
Through regex alone.. 仅通过正则表达式。
$str="Big black books being kept in a black bag of a beautiful babe";
$pattern="/^([^b]*b){1,6}[^b]*$/";
if(!preg_match($pattern,$str,$matches))
{
echo "Please use upto six bs";
}else
{/*do nothing*/}
print_r($matches);
and note that this must except atleast one single b. 并请注意,这至少要至少一个b。 If you want to match also the line which don't have any single b
then use /^([^b]*b){0,6}[^b]*$/
如果您还想匹配没有单个b
的行,则使用/^([^b]*b){0,6}[^b]*$/
Add case-insensitive modifier i
if you want to count also for capital B
's. 如果您还想计算大写字母B
的大小,请添加不区分大小写的修饰符i
。
Explanation: 说明:
^
start of the line. ^
行首。 ([^b]*b){1,6}
It matches (zero or more non-b characters and a b
)(from 1 to 6 times). ([^b]*b){1,6}
匹配(零个或多个非b字符和a b
)(1到6次)。 So this ensures that there must be character b
exists min of 1 time and a max of 6 times. 因此,这确保必须存在至少1次且最多6次的字符b
。 [^b]*
Matches any char but not of b
, zero or more times. [^b]*
匹配任何char,但不匹配b
,零次或多次。 This ensures that there are no more further b
exists. 这样可以确保不再存在b
。 $
End of the line boundary.. $
线边界的末端.. Try using match count. 尝试使用匹配计数。
<?php
$str="Big black books being kept in a black bag of a beautiful babe";
preg_match_all("/(b)/i",$str,$matches);
if(isset($matches[1]) && count($matches[1]) > 6 )
{
echo "Please use six bs";
}else
{/*do nothing*/}
print_r($matches);
?>
I think you want to count the number of Bs in the whole string while your regular expression counts them only in rows. 我想您想计算整个字符串中B的数量,而您的正则表达式只计算行中的B数。 ie "bbb" or just "b" would return a match. 即“ bbb”或“ b”将返回一个匹配项。
Try using substr_count
to achieve what I think you want. 尝试使用substr_count
实现我认为想要的功能。 Here's an example. 这是一个例子。
<?php
$str = "Big black books being kept in a black bag of a beautiful babe";
if(substr_count($str, "b") > 6)
echo "Six is the limit...";
else
echo "Doing nothing...";
?>
But of course, it won't really help if you want to see the found matches. 但是,当然,如果您想查看找到的匹配项并不会真正有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.