Solution:1
You can use regular expressions and the function preg_match_all
:
$value = "This is a test string.";
$length = preg_match_all ('/[^ ]/' , $value, $matches);
echo $length; //18
Here you can find a working example: https://3v4l.org/IPlJi
explanation:
Between [^
and ]
you have to add all characters which should not be count to the length of the string. For example: if you want to filter out the character i
and (space) you have to set the following pattern:
[^ i]
.
Code to filter i
and (space):
$value = "This is a test string.";
$length = preg_match_all('/[^ i]/' , $value, $matches);
echo $length; //15
be carefull with some characters:
If you want to exclude one of the following characters .^$*+?()[{\|
you have to escape them with \
. If you want to exclude the .
too, you have the following code:
$value = "This is a test string.";
$length = preg_match_all ('/[^ \.]/' , $value, $matches);
echo $length; //18
how to test your pattern:
If you want to test your regular expressions for preg_match_all
or other functions like that, you can use the following tool: http://www.phpliveregex.com/