user5237857
user5237857

Reputation: 118

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?

Upvotes: 1

Views: 45

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174706

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..

Upvotes: 5

Nijraj Gelani
Nijraj Gelani

Reputation: 1466

I think you want to count the number of Bs in the whole string while your regular expression counts them only in rows. i.e. "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.

Upvotes: 0

Vegeta
Vegeta

Reputation: 1317

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

Upvotes: 0

Related Questions