I'm newbie in the world of regular expression.
I want to create an expression can match X character N times in a string.
for example:
X = t
N = 2
then it should match string test
or tit
or tt
.
I'm newbie in the world of regular expression.
I want to create an expression can match X character N times in a string.
for example:
X = t
N = 2
then it should match string test
or tit
or tt
.
Solution using RegEx
/^([^t]*t[^t]*){2}$/
Where N = 2
^
Anchors the regex at the start of the string.
[^t]*
Negated character class, matches anything other than t
. *
Quntifies it any number of times
t
Which is followed by a t
[^t]*
Further followed by anything other than t
{2}
Quantifies the pattern 2
times. That is it ensures that not t zero or more times followed by t and followed by not t zero or more time. The entire thing must occure 2 times
$
Anchors the regex at the end of the string.
Test
$X='t';
$N=2;
$regex="/^([^".$X."]*".$X."[^".$X."]*){".$N."}$/";
echo preg_match($regex, "test" );
// => True
Solution using substr_count
The substr_count
function returns the number of occurence of an substring in a string
$X='t';
$N=2;
if ( substr_count('test', $X ) == $N )
//The string is ok
else
//The string is not ok