2

I try to create a Helper function which shall replace the short names of language to their full names.

I have a constants file which looks like this (using laravel that is why the constant looks like this):

<?php

return [
    'languages' => [
        'names' => [
            'Bulgarian' => 'bg',
            'Danish' => 'da',
            'German' => 'de',
            'English' => 'en'
            ...
        ],
    ]
];

My function so far looks like this:

public static function replaceName($string = '')
{
    $langName = Config::get('constants.languages.names');
    foreach($langName as $langKey => $langValue)
    {
        $search  = array($langValue);
        $replace = array($langKey);
    }
    return str_replace($search, $replace, $string);
}

But it still does not work any ideas?

4
  • 1
    You want to replace 'German' with 'de'? Then do return str_replace(array_keys( $langName), $langName, $string); else return str_replace($langName,array_keys( $langName), $string); Commented Dec 22, 2016 at 16:08
  • 1
    No I want to replace de with German Commented Dec 22, 2016 at 16:10
  • Did you now how many word have the de part in it? Commented Dec 22, 2016 at 16:11
  • in my case there can only be one do not worry :) Commented Dec 22, 2016 at 16:12

2 Answers 2

3

you can use array_search as:

array_search('de', Config::get('constants.languages.names')) // returns German

From the docs

Searches the array for a given value and returns the first corresponding key if successful.

Sign up to request clarification or add additional context in comments.

Comments

0

One way to rome.

public static function replaceName($string = '')
{
  $langName = Config::get('constants.languages.names');
  foreach($langName as $langKey => $langValue)
  {
    $search[]  = " $langValue ";
    $replace[] = " $langKey ";
  }
  return str_replace($search, $replace, $string);
}

It replaces only full words with spaces before and after it!

We dont want to Ben become BEnglish! ;) If this is not needed, remove the spaces.

##############################################

When $string only has de as content, then:

public static function replaceName($string = '')
{
  $langName = array_flip(Config::get('constants.languages.names'));
  return isset($langName[$string])?$langName[$string]:$string;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.