toffler toffler - 2 months ago 19
PHP Question

PHP preg_replace to keep only capital letters of a string

what I'm looking for is a

preg_replace
, 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 :)

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

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 />";
}
die;


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:

preg_replace('/[^A-Z]/','',$string);

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".