简体   繁体   中英

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:

<?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. If you want to match also the line which don't have any single b then use /^([^b]*b){0,6}[^b]*$/

Add case-insensitive modifier i if you want to count also for capital B 's.

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). So this ensures that there must be character b exists min of 1 time and a max of 6 times.
  • [^b]* Matches any char but not of b , zero or more times. This ensures that there are no more further b exists.
  • $ 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. ie "bbb" or just "b" would return a match.

Try using substr_count to achieve what I think you want. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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