[PHP] Counting Twitter characters

Quoting their official docs

To the human eye the length is clearly four characters. Depending on how the data is represented this could be either five or six UTF-8 bytes. Twitter does not want to penalize a user for the fact we use UTF-8 or for the fact that the API client in question used the longer representation. Therefore, Twitter does count “caf√©” as four characters no matter which representation is sent.

The code to get a string’s length (like twitter) in php is to use the multi-byte strlen function


mb_strlen(utf8_decode(trim($tweet)), 'utf-8');

strlen would give the same result after using the decode function.

[PHP] Validation

Validation is headache. Fortunately, this function makes it better. Sample usage is as follows:


function fields_validation($field){
	$validation_rules = array();
	if(isset($field->slug)){
		$slug = $field->slug;
	} else {
		$slug = sanitize_title($field->label);
	}
	$label = $field->label;
	if(intval($field->minLength) != '0'){
		$minLength = intval($field->minLength);
		$validation_rules[] = "length>=$minLength,$slug,$label must be at least $minLength characters long.";
	}
	if(intval($field->maxLength) != '0'){
		$maxLength = intval($field->maxLength);
		$validation_rules[] = "length<=$maxLength,$slug,$label must be $maxLength characters long maximum.";
	}				
	if($field->isEmail){
		$validation_rules[] = "valid_email,$slug,Please enter a valid email address.";
	}
	return $validation_rules;
}

and then call the function itself

$validation_rules = fields_validation($field);
$errors = validateFields($_POST, $validation_rules);

$errors will be an array. A simple !empty($errors) will check for errors.

The conditions represents the rule that must be true in order not to produce an error. For example, length <= $maxLength means that the length must be less than max length to pass the check. $slug is the name of the form’s field.