PHP Regular Expressions Counting starting consonants in a string
I need to figure out how many starting consonants a word has. The number is used later in the program. The code below works, I am wondering if it can be done with a regex.
$mystring ="SomeStringExample";
$mystring2 =("bcdfghjklmnpqrstvwxyzABCDFGHJKLMNPQRSTWVXYZ");
$var = strspn($mystring, $mystring2);
Using regex like this
$regex= ("^[b-df-hj-np-tv-z]");
$var = strspn($mystring, $regex);
Doesn't work as strspn expects two lines.
source to share
This is one way to do it using preg_match
:
$string ="SomeStringExample";
preg_match('/^[b-df-hj-np-tv-z]*/i', $string, $matches);
$count = strlen($matches[0]);
The regex matches zero or more ( *
) case-incompatible ( /i
) consonants [b-df-hj-np-tv-z]
at the beginning ( ^
) of the string and stores the matched content in an array $matches
. Then it's just a matter of getting the length of the string using strlen
. Not the most elegant solution, but I believe it answers your question.
source to share
it will be done. The result of the whole regex will be stored in $matches[0]
, and the first parenthesis that matches the text will be stored in $matches[1]
, so searching for the length $matches[1]
(or even $matches[0]
, since the capture is a full regex) will be equivalent to what your code is doing. But performance might not be better
$mystring ="SomeStringExample";
$regex= ("/^([b-df-hj-np-tv-z]*)/i");
preg_match_all($regex,$mystring,$matches);
echo sizeof($matches[1]);
source to share