how to detect telephone numbers in a text (and replace them)?

后端 未结 4 473
名媛妹妹
名媛妹妹 2020-12-09 19:21

I know it can be done for bad words (checking an array of preset words) but how to detect telephone numbers in a long text? I\'m building a website in PHP for a client who n

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 19:55

    Welcome to the world of regular expressions. You're basically going to want to use preg_replace to look for (some pattern) and replace with a string.

    Here's something to start you off:

    $text = preg_replace('/\+?[0-9][0-9()\-\s+]{4,20}[0-9]/', '[blocked]', $text);
    

    this looks for:

    a plus symbol (optional), followed by a number, followed by between 4-20 numbers, brackets, dashes or spaces, followed by a number

    and replaces with the string [blocked].

    This catches all the obvious combinations I can think of:

    012345 123123
    +44 1234 123123
    +44(0)123 123123
    0123456789
    Placename 123456 (although this one will leave 'Placename')
    

    however it will also strip out any succession of 6+ numbers, which might not be desirable!

提交回复
热议问题