PHP function localizedString

Last week I was looking for a string PHP function that does a very basic thing:
Take a string with some unknown number of variables in the string and replace them.

E.g.: “Your search for {1} has no results.”
or: “Page {1} of {2}

This is very handy for translations. In some languages you cannot just simply translate the word “page” and the word “of” because the case of the words might be different depending on the context of the word.
The solution is to translate the complete sentence and replace the variables.

Surprisingly, I could not find a quick solution for PHP although it is commonly used in .NET and JAVA.
So I had to build one myself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
     /**
     * Returns a string with some variables replaced
     * E.g.:
     * $str    = "Page {1}  ({1}/{2})";
     * $arg1   = "1";
     * $arg2   = "5";
     * echo localizedString($str,$arg1,$arg2);
     * would return: Page 1 (1/5)
     */

    function localizedString() {

      $patterns     = array();
      $replacements = array();
      $text         = func_get_arg(0);
      $numArgs      = func_num_args();

      for ($i = 1; $i < $numArgs; $i++) {
          $patterns[]     = '/\{'.$i.'\}/';
          $replacements[] = func_get_arg($i);
      }

      return preg_replace ($patterns, $replacements, $text);
    }

You can call the function like this:

1
2
3
4
$str    = "Sorry, the code you entered was invalid. {1}Go back {2} to try again.";
$arg1   = '<a href="history.go(-1)">';
$arg2   = "</a>";
echo localizedString($str,$arg1,$arg2);

Related posts

Tags: ,

One Response to “PHP function localizedString”

  1. Mayor Brain says:

    Exactly what I was looking for.

    Thanks.

Leave a Reply