PHP - Count total words in a regex pattern -
take following php regular expression:
/^(what is|tell me) name$/
i want determine total number of available words within pattern. correct answer 4
seeing following combinations compatible:
what name => 4 words tell me name => 4 words
a simple count(explode(' ', '/^(what is|tell me) name$/'))
not going cut it, seeing explode
function return following:
['/^(what', 'is|tell', 'me)', 'your', 'name$/']
...which defines 5 "words", when really, 4 available within pattern.
here's example:
/^(my|the) name (\w+)$/ => 4 words
is there function available can utilise, or have create tech 1 scratch?
kudos if anyone's willing give shot.
this extremely ugly, maybe can use of logic? seams work.
i basicly split string 2 different strings. $first_string
part between parentheses ()
. explode string on |
, count whitespaces in new string +1
.
the second part of string $second_string
strip out non alphabetic chars , double whitespaces , count words.
finaly add $first_string + $second_string
final result.
one weakness if have string (something | else)
, don't think method of counting whitespaces can handle different amounts of words on each site of |
.
<?php $string='/^(my|the) name (\w+)$/'; $pattern='/\(([^\)]+)\)/'; // text between () $pattern2 = '([^a-za-z0-9 $])'; // non alphabetic chars except $ preg_match($pattern,$string, $first_string); // text $first_string=explode('|', $first_string[0]); $new_string = preg_replace($pattern, '', $string); $new_string2 = preg_replace($pattern2, '', $new_string); $new_string2 = removewhitespace($new_string2); // count words $first_string=substr_count($first_string[0]," ")+1; $second_string = sizeof(explode(" ", $new_string2)); // count words // removes double white space function removewhitespace($text) { $text = preg_replace('/[\t\n\r\0\x0b]/', '', $text); $text = preg_replace('/([\s])\1+/', ' ', $text); $text = trim($text); return $text; } echo $first_string+$second_string; // final result ?>
Comments
Post a Comment