4

I come from update my Coder module to the v1.3 and when I go to check one custom module I see the following message:

Line 71: in most cases, replace the string function with the drupal_ equivalent string functions

$node_type = substr($form_id, 0, -10);

Line 187: in most cases, replace the string function with the drupal_ equivalent string functions

$info->language = ($info->language == 'und' || empty($info->language)) ? t('Undetermined') : ucfirst($info->language);

So, why I need to use the drupal_substr() and drupal_ucfirst() in this case? And in general why to use the drupal_ equivalent functions when we have the php functions?

3

1 Answer 1

5

Most PHP string function don't handle unicode characters. For this you need to use their mb_* variants, which are (were?) not always available on some host. The drupal_* variants ensure unicode compatibility. They wrap mb_* functions and provide pure PHP implementations for when they are not available.

So, this recommendation is there to ensure portability of your code across hosts.

5
  • This is the right answer.
    – Kevin
    Commented Sep 22, 2016 at 17:44
  • It's a rule of thumb to use the Drupal API functions instead of PHP functions when available.
    – No Sssweat
    Commented Sep 24, 2016 at 0:29
  • @NoSssweat Even if I don't use unicode? Commented Sep 24, 2016 at 1:07
  • @AdrianCidAlmaguer I just noticed in drupal_substr() it says "the usage of PHP's normal strpos/substr is safe and much faster." Hmmm this is probably the exception to the rule of thumb.
    – No Sssweat
    Commented Sep 24, 2016 at 2:11
  • 1
    The complete sentence is "Note that for cutting off a string at a known character/substring location, the usage of PHP's normal strpos/substr is safe and much faster.", so that's a specific usage of the function where the original PHP function is considered safe. You always use unicode when working with Drupal as it use only UTF-8. Commented Sep 24, 2016 at 19:46

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.