user6345002 user6345002 - 1 year ago 65
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download