Drupal – Leveraging built in string functions in custom modules
Drupal includes native versions of a few common php string functions; strlen() for example is called with drupal_strlen().
drupal_strlen counts the amount of characters in a UTF-8 string vs. counting the bytes of a string. Not a huge difference perhaps but according to the brief documentation: This is less than or equal to the byte count. So if you want better accuracy then user the drupal_str function
I was introduced to these functions a few years ago, when using the Drupal coder module: http://drupal.org/project/coder.
I wanted to quickly prepare a custom module to use the drupal flavored functions today and thought I’d share the regex I used in to find & replace:
(DreamWeaver regex)
Find:
([ (.]+)(substr|strlen|strtolower|strtoupper|ucfirst)
Replace:
$1drupal_$2
A quick replace and you’re Drupal friendly.
More information about all the drupal string functions can be found in the docs: 6 includes/unicode.inc or 7 includes/unicode.inc and here’s an excerpt of the table:
Name | Description |
---|---|
drupal_strlen | Count the amount of characters in a UTF-8 string. This is less than or equal to the byte count. |
drupal_strtolower | Lowercase a UTF-8 string. |
drupal_strtoupper | Uppercase a UTF-8 string. |
drupal_substr | Cut off a piece of a string based on character indices and counts. Follows the same behavior as PHP’s own substr() function. |
drupal_ucfirst | Capitalize the first letter of a UTF-8 string. |