Aswin Lutchanah

Hybrid Social Media Specialist + Php/MySql Developer Metz (Développeur Php/MySql Metz) + SEO-SMO

Php function – check if characters in a string are numerical

I was looking for a way to check if a string contained only numerical values.  I thought that the php function is_numeric() would do the job. I was wrong.

  1. echo is_numeric(555); // 1
  2. echo is_numeric(55.55); // 1
  3. echo is_numeric(+55.55); // 1
  4. echo is_numeric(-55.55); // 1
  5. echo is_numeric(+55.55); // 1

Facebook ids (for developers)

Php has a function (ctype_digit()) that suits my needs concerning this matter. In fact, I was looking for a way to check the different ids provided by Facebook and that transited through my Facebook Apps. I needed a server side verification for those ids. As you might already know, Facebook ids tend to be very long and considering them as integers could end up being very tricky. So, php functions like is_int() or intval() are useless in this case because they are system dependent (32 bits, 64 bits, etc..).

Php function ctype_digit()

ctype_digit() checks whether the whole string contains only digits ! Therefore, you don’t bother about the length of the string (Facebook id or any other id). With this php function, you will know if it contains only digits without any signs such as “+,-,.,etc…”.

  1. echo ctype_digit(‘555’); // 1
  2. echo ctype_digit(‘55.55’); //
  3. echo ctype_digit(‘+55.55’); //
  4. echo is_numeric(‘-55.55’); //
  5. echo ctype_digit(‘-+55.55’); //

Alternative with a regular expression

This was my initial solution to the problem.

  1. function isValidBigInteger($sString) {
  2.         return preg_match(‘/^[0-9]+$/’, $sString);
  3. }
  4. echo isValidBigInteger(‘555’);//1
  5. echo isValidBigInteger(’55b’);//0

Posted In: PHP, SMO, Web Development

Tags: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*