Sunday, December 9, 2012

How to properly encode email subject

When we want to send a email with non US characters in email subject it is important to properly encode it. Below is the most simple code that does just that (thanks Gasper for help).
public function email_subject_encode($in_str, $charset = 'UTF-8') {

    #remove all non utf8 characters
    $in_str = mb_convert_encoding($in_str, $charset, $charset);

    #Remove non printable character (i.e. below ascii code 32).
    $in_str = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/u',
                           '', $in_str);

    #encode email subject
    $out_str ="=?utf-8?b?".base64_encode($in_str)."?=";

    return $out_str;

Tuesday, December 4, 2012

Parsing date string

If you are non US user you will stumble on a problem how to parse date strings that are in non US format i.e. 31.12.2012. Code below does just that. First we use regular expression to extract month, date and year and if it is a valid date then convert it to Datetime object.

public function ParseForDateTimeValue ($strText) {
  if ($strText != "") {
    // RegExp taken from
        $strText, $arr_parts)) {

      $month = ltrim($arr_parts[2], '0');
      $day = ltrim($arr_parts[1], '0');
      $year = $arr_parts[3];

      if (checkdate($month, $day, $year)) {
        return new DateTime(date('Y-m-d H:i:s', 
         mktime(0, 0, 0, $month, $day, $year)));
  return NULL;