phpregex

How to create a custom phone number regex


I'm using php and searching for the right regex form my country phone number. I'm not good with regex but i did some research on the possible patterns of my country phone number's and those are:

plz help me save my day !!


Solution

  • Assuming you removed all spaces (and perhaps other invalid characters):

    ((\+|00)216)?[0-9]{8}
    

    This regex should match all provided examples.

    Update:

    Here is the "complete" regex. It is based on a Wikipedia article:

    ((\+|00)216)?(74|71|78|70|72|9|4|2|5|73|75|76|77|79)[0-9]{6}
    

    What I don't know is how to handle single-digit area codes, perhaps the following regex is better:

    ((\+|00)216)?(74|71|78|70|72|09|04|02|05|73|75|76|77|79)[0-9]{6}
    

    Update 2:

    The final solution, this time based on another document:

    ((\+|00)216)?([2579][0-9]{7}|(3[012]|4[01]|8[0128])[0-9]{6}|42[16][0-9]{5})