user6345002 user6345002 - 1 month ago 6
PHP Question

Need to count german char in a string php

I need to count all german's char in a string with php.

I tryed like this:

$pattern = '/[äüöÄÜÖß]/';

$address = "Knnöstraße";

$counting = 0;

if(preg_match($pattern, $address )) {
$counting ++;
}

echo $counting;


But it return me only 1. What s the best way to count special char?

With preg_all_match function it return me 4, but it must be 2:

preg_match_all($pattern, $address, $matches, PREG_SET_ORDER);

echo count($matches);

Answer

You could count a difference between original string and string without special german characters, like the following:

echo (mb_strlen($address, 'UTF-8') - strlen(str_replace(['ä', 'ü', 'ö', 'Ä', 'Ü', 'Ö', 'ß'], '', $address))); //2