Difference between revisions of "String API"

Jump to: navigation, search
(get_string(): using different identifiers for the two examples to help users to distinguish between them)
m (Get rid of the link to the obsolete page Places_to_search_for_lang_strings)
Line 10: Line 10:
===Adding language file to plugin===
===Adding language file to plugin===
Language support for plugin(s) is added by creating a '''lang''' subdirectory in the plugin directory. The structure of the '''lang''' directory is then the same as the "main" language directory.
Language support for plugin(s) is added by creating a '''lang''' subdirectory in the plugin directory. The structure of the '''lang''' directory is then the same as the "main" language directory.
Plugin language file name needs to start with the generic type for the plugin. For example all questiontype plugins '''must''' be prefixed '''qtype_''', all authentication plugins '''auth_'''. Moodle uses this prefix to identify the [https://docs.moodle.org/dev/Places_to_search_for_lang_strings#Defining_the_search_path.28s.29 language search path.]
Example for adding language support file for Drag & Drop optional question type
Example for adding language support file for Drag & Drop optional question type

Revision as of 11:31, 6 September 2017


The String API is how you get language text strings to use in the user interface. It handles internationalisation issues, and will use a number of settings and environment variables to present the best text to every user. Moodle has a mechanism that allows a number of places to be searched (in order) to find language strings. This enables language strings to be packaged with plugins and avoids the step of having to copy the language files over to the language directory when a plugin is installed.

Moodle also provide general string functions like substr, strlen etc. for multibyte safe, string operations. It uses mbstring or iconv for UTF-8 strings and falls back to typo3.

Basic concepts

When it is required to lookup a string, two basic items of information are required.

  1. Name of the plugin language file in which it can be found.
  2. Name of the string. For example, get_string('editingquiz', 'quiz') returns "Editing quiz" in the current language.

Adding language file to plugin

Language support for plugin(s) is added by creating a lang subdirectory in the plugin directory. The structure of the lang directory is then the same as the "main" language directory.

Example for adding language support file for Drag & Drop optional question type

   Description: Drag & Drop optional question type
   Module type: qtype_
   Module name: qtype_dragdrop
   Language file location (English): contrib/plugins/question/type/dragdrop/lang/en/qtype_dragdrop.php


  • Module names cannot have numbers in them (only A-Z, a-z and underscore). This might be an issue to consider if you are moving from an existing architecture.

Adding name of string in language file

Name of the string is added to a pre-defined array $string. If you want to a string "Editing Quiz" with string name "editingquiz" in Drag & Drop plugin then add the following in qtype_dragdrop.php language file.

//string name added for 'Editing Quiz'
$string['editingquiz'] = 'Editing Quiz';
//Help string for 'Editing Quiz' (optional)
$string['editingquiz_help'] = 'Help for editing quiz';


  • Help string name should be suffixed with _help. Look at Help strings for more details.


String functions are defined in

  1. lib/moodlelib.php - locale related functions
  2. lib/textlib.class.php - general string functions (substr, strlen etc.)

Functions and examples

There are three main functions, used in moodle for getting/displaying the localised string, based on user preferred language.


Returns a localised string for current user.

Example for displaying string "This is my plug-in" in any language that supports on your site, then you need to use the following identifier in language file (located in appropriate lang directory)

  $string['plugintitle'] = 'This is my plug-in';

If you want to display this string in any supported language, then you would use this function.

  echo get_string('plugintitle', 'module_pluginlangfilename');

If you want to substitute value in the language string then use {$a} for substituting value. $a is an object, string or number that can be used within translation strings. The variable has to be $a, and it has to be in single quotes. For example, if you want to display answer number in Drag & drop plugin then add

  $string['answerno1'] = 'Answer {$a}'; //Substituting string/integer
  $string['answerno2'] = 'Answer {$a->name}'; //Substituting object member

in qtype_dragdrop.php (Drag & Drop language file). And call it using

  //Get string by substituting integer. 
  get_string('answerno1', 'qtype_dragdrop', $number);
  //Get string by substituting object member integer
  $user->number = 10;
  get_string('answerno2', 'qtype_dragdrop', $user);

In Moodle 2.3 there is a new argument to this function $lazyload. Setting $lazyload to true causes get_string to return a lang_string object rather than the string itself.

  $stringobject = get_string('answerno', 'qtype_dragdrop', $number, true);

The fetching of the string is then put off until the string object is first used. The object can be used by calling it's out method or by casting the object to a string, either directly e.g.


or indirectly by using the string within another string or echoing it out e.g.

  echo $stringobject;
return "



Note: using $lazyload and attempting to use the string as an array key will cause a fatal error as objects cannot be used as array keys.


Converts an array of string names to localised strings for a specific plugin. lazy loading is not supported in this function.

  $txt = get_strings(array('enable', 'disable', 'up', 'down', 'none'), 'qtype_dragdrop');
  echo $txt->up;  //Display localised string for up
  echo $txt->down //Display localised string for down


Prints out a translated string by using get_string() function

lang_string class

In Moodle 2.3 a special class (lang_string) is used to create an object representation of a string request. In this case string processing doesn't occur until the object is first used. The class was created especially to aid performance in areas where strings were required to be generated but were not necessarily used. As an example the admin navigation tree when generated uses over 1500 strings, of which normally only 1/3 are ever actually printed at any time. The performance advantage is achieved by not actually processing strings that aren't being used, as such reducing the processing required for the page.

lang_string class can be used in two ways

  1. Setting $lazyload (forth argument of the get_string function), to true.
  $string = get_string('yes', 'qtype_dragdrop', null, true);
  1. Direct instantiation
  $string = new lang_string('yes', 'qtype_dragdrop', null, 'en');

String manager

Most of function listed above are just handful wrappers for the methods provided by the string manager class. Some strings related functionality is available only via directly calling the manager's methods.

$stringman = get_string_manager();

The factory function get_string_manager() returns singleton instance of core_string_manager_install in early stages of the site installation, or instance of core_string_manager_standard in all normal situations. These managers implement interface core_string_manager. Methods provided by the interface are

Returns the given component string localised in the given language. Can be used to obtain the translation of the string in the other language than the current user's language.
Does the given string actually exist? This is typically checked by a code like
if (get_string_manager()->string_exists('stringidentifier', 'component_name')) {
    // Do something.
Has the string been deprecated? See String deprecation for details.
Returns a localised list of all country names, sorted by country keys.
Returns a localised list of languages, sorted by code keys.
Checks if the translation exists for the given language.
Returns localised list of installed language packs.
Returns localised list of known currencies.
Loads all strings for one component.
Invalidates all caches, should the manager use some.
Returns string revision counter.

Custom string managers

Moodle 2.9 Plugins can provide custom implementation of the string manager. This is supposed to be used in experimental and/or development scenarios only, not in typical production environment. See MDL-49361 for use cases and implementation details. An example of such an implementation can be found at moodle-local_stringman.git repository.

// Custom string manager class can be defined in the main config.php file.
$CFG->customstringmanager = '\local_stringman\dummy_string_manager';

textlib (core_text) class

textlib class provide pool of safe functions to operate on UTF-8 text. textlib provide set of static functions to operate on strings and gets included in setup.php

Moodle 2.6 In Moodle 2.6 the textlib class was renamed to core_text.


Locale aware sorting, the key associations are kept, values are sorted alphabetically.


Returns the utf8 string corresponding to the unicode value


Converts the text between different encodings. It uses iconv extension with //TRANSLIT parameter, fall back to typo3


Generate a correct base64 encoded header to be used in MIME mail messages.


Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8


Converts upper unicode characters to plain ascii, the returned string may contain unconverted unicode characters.


Multibyte safe strlen() function, uses iconv for utf-8, falls back to typo3.


Find the position of the first occurrence of a substring in a string. UTF-8 ONLY safe strpos(), uses iconv.


Find the position of the last occurrence of a substring in a string. UTF-8 ONLY safe strrpos(), uses iconv.


Multibyte safe strtolower() function, uses mbstring, falls back to typo3.


Makes first letter of each word capital - words must be separated by spaces.


Multibyte safe strtoupper() function, uses mbstring, falls back to typo3.


Multibyte safe substr() function, uses iconv for utf-8, falls back to typo3.


Removes the BOM from unicode string. more info


Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;


When should I use a lang_string object?

The lang_string object is designed to be used in any situation where a string may not be needed, but needs to be generated. The admin navigation tree is a good example of where lang_string objects should be used. A more practical example would be any class that requries strings that may not be printed (after all classes get renderer by renderers and who knows what they will do ;))

When should I not use a lang_string object?

Don't use lang_strings when you are going to use a string immediately. There is no need as it will be processed immediately and there will be no advantage, and in fact perhaps a negative hit as a class has to be instantiated for a lang_string object, however get_string won't require that.

Limitation of lang_string

lang_string object cannot be used as an array offset. Doing so will result in PHP throwing an error. (You can use it as an object property!)

How to compare strings properties in two object

collatorlib_property_comparison class can be used to compare properties of two objects

See also