Ultimate way to find phone numbers in PHP string with preg_replace

前端 未结 4 1804
无人及你
无人及你 2020-12-21 21:35

working on a project right now where we have large amount of text strings that we must localize phone numbers and make them clickable for android phones.

The phone n

相关标签:
4条回答
  • 2020-12-21 22:04

    Perhaps something like this:

    /(\+\d+)?\s*(\(\d+\))?([\s-]?\d+)+/
    
    • (\+\d+)? = A "+" followed by one or more digits (optional)
    • \s* = Any number of space characters (optional)
    • (\(\d+\))? = A "(" followed by one or more digits followed by ")" (optional)
    • ([\s-]?\d+)+ = One or more set of digits, optionally preceded by a space or dash

    To be honest, though, I doubt that you'll find a one-expression-to-rule-them-all. Telephone numbers can be in so many different formats that it's probably impractical to match any possible format with no false positives or negatives.

    0 讨论(0)
  • 2020-12-21 22:15

    Try the following:

    preg_match_all('/\+?[0-9][\d-\()-\s+]{5,12}[1-9]/', $text, $matches);
    

    or:

    preg_match_all('/(\+?[\d-\(\)\s]{8,20}[0-9]?\d)/', $text, $matches);
    
    0 讨论(0)
  • 2020-12-21 22:23

    I guess this might do it for these cases?

    preg_replace("/(\+?[\d-\(\)\s]{7,}?\d)/", '<a href="tel:$1">number</a>', $str);
    

    Basicly I check if it may start on +. It doesn't have to. Then I check if it got numbers, -, (, ) and spaces with at least 8 cases so it doesn't pick low non-phone numbers.

    0 讨论(0)
  • 2020-12-21 22:27

    Not sure that there is a library for that. Hmmmm. Like any international amenities, telephone numbers are standardised and there should be a format defining telephone numbers as well. E.164 suggests recommended telephone numbers: http://en.wikipedia.org/wiki/E.164 . All open-source decoding libraries are built from reading these standard formats, so it should be of some help if you really cant find any existing libs

    0 讨论(0)
提交回复
热议问题