php editor Banana pointed out that sometimes we need to remove characters that do not meet a specific mask from a string, which requires the use of some functions in PHP. This article will introduce how to use PHP functions to filter out the parts of the string that do not match the mask and calculate its length. Let’s take a look at the specific implementation method!
PHP returns the length of the string that does not match Mask
In php, you can use the preg_match()
function to match the part of the string that matches the specified pattern (mask). To return the length of a string that does not match mask, use the following steps:
preg_match()
Match string:
preg_match()
The function will attempt to match the given string with a regular expression pattern. If a match is found, it returns 1 and stores the captured group in $matches
array. $mask = "/[a-z] /"; // Regular expression matching lowercase letters preg_match($mask, $string, $matches);
preg_match()
returns 0, it means no match was found. At this point, the entire string does not match the mask. You can get the length of a string using the strlen()
function: if (preg_match($mask, $string, $matches) == 0) { $length = strlen($string); }
preg_match()
finds a match, $matches[0]
will contain the string matching the entire mask. You can get its length using the strlen()
function: if (preg_match($mask, $string, $matches) > 0) { $length = strlen($matches[0]); }
$non_matching_length = strlen($string) - $length;
Finally, the following code implements the above steps:
function getNonMatchingLength($string, $mask) { if (preg_match($mask, $string, $matches) == 0) { return strlen($string); } elseif (preg_match($mask, $string, $matches) > 0) { $matching_length = strlen($matches[0]); $non_matching_length = strlen($string) - $matching_length; return $non_matching_length; } else { return 0; } } $string = "This is a string with non-numeric characters."; $mask = "/[0-9] /"; // Regular expression to match numbers $non_matching_length = getNonMatchingLength($string, $mask); echo "Length of the non-matching part: $non_matching_length";
Output:
Length of the non-matching part: 41
The above is the detailed content of PHP returns the length of the string that does not match the mask. For more information, please follow other related articles on the PHP Chinese website!