Click here to Skip to main content
15,867,765 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm teaching my self on how to do a quantifier {2} so I read that this is based on exactly 2 occurrences but my if else is saying this is not mentioned 2 times why is that?

PHP
<?php 
$string = 'sasa sasa'; 
if(preg_match('/sasa{2}/',$string)) 
{ 
echo 'sasa is mentioned 2 times'; 
} 
else 
{ 
echo "sasa is not mentioned 2 times"; 
} 
?>


What I have tried:

Google search but I can't find that much easy to understand info on this.
Posted
Updated 9-Jan-18 21:46pm
Comments
Peter_in_2780 9-Jan-18 22:56pm    
I haven't got my regex tools to hand, but off the top of my head, your regex is set up to match "sasaa". In other words, the quantifier refers to the last matchable item, which is a single character. Try '/(sasa){2}/'

Even then, you'll need to account for the whitepace.

You are doing wrong usage of quantifier.
/sasa{2}/

will match only if string contain "sasaa"
if you want to know if "sasa" is 2 times in a string, you need to use "/sasa/" and ask number of matches.

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
 
Share this answer
 
v2
Comments
Peter_in_2780 9-Jan-18 23:26pm    
No! /sasa{2}/ matches "sasaa" not "sasasasa". See my comment to OP.
Patrice T 9-Jan-18 23:28pm    
Oops
As already mentioned, you will have to count the number of matches. This can be done with PHP: preg_match_all - Manual[^] which returns the number of matches:
PHP
<?php.
$string = 'sasa sasa';.
$count = preg_match_all('/sasa/', $string, $matches);
echo "sasa is mentioned $count times\n";.
?>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900