toffler toffler - 1 year ago 55
PHP Question

PHP preg_replace to keep only capital letters of a string

what I'm looking for is a

, that accept several company name inputs or Brands like "DPD", "Deutscher Paket Dienst", "Teenage Mutant Ninja Turtles".

The output shoud allways be the according abbreviation. The former inputs should therefore output: "DPD", "DPD", "TMNT", so only the capital letters should pass the replace.

please help :)

There is not much code to provide, i just don't get the basics of

My code so far is this:

$company_names = array("DPD", "Deutscher Paket Dienst");

foreach($company_names as $name)
$res = preg_replace('/([A-Z])/', "$1", $name);
echo $res. "<br />";

which just outputs the input. :)

Answer Source

To keep uppercase letters only simply match for everything NOT an uppercase letter and remove it, like so:


This will turn "Deutscher Paket Dienst" into "DPD" but leave something already abbreviated, like "TNT" as "TNT".

It will fail with strings like "FedEx" though as that would become "FE".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download