filtering using regex and returning the matched number

后端 未结 1 600
太阳男子
太阳男子 2021-01-28 19:41

Here i am trynig to filter the specific phone numbers from text using regex. Phone name may have exploits like this.

4023one345233 should be considered as <

相关标签:
1条回答
  • 2021-01-28 20:02

    If I understand your question correctly you want to replace a string of numbers (possibly containing written numbers) with asterisks. The number of asterisks must be equal to the number of characters in the string.

    In the code below, the regex matches strings that contain 3 to 7 numbers.

    $s = "123 onetwothree 1two3 one dog";
    $new_words = array();
    $numbers = array();
    $pattern = "#(\d|zero|one|two|three|four|five|six|seven|eight|nine){3,7}#i";
    foreach(explode(" ", $s) as $word) {
        if(preg_match($pattern, $word, $matches)) {
            $new_words[] = str_repeat("*", strlen($word));
            $numbers[] = $matches[0];
        } else {
            $new_words[] = $word;
        }
    }
    
    $new_s = implode(" ", $new_words);
    print $new_s . "\n";
    print implode(" ", $numbers) . "\n";
    

    which gives:

    *** *********** ***** one dog
    123 onetwothree 1two3
    

    The regex in your code is extremely long and adding 'zero|one|...' to the regex might not be feasible for you. Another solution could be to:

    • get the number of characters of each word in your string: $word_lengths
    • replace written numbers with their numerical values. e.g. 'one' becomes '1'
    • match with your long regex
    • if there is a match, create a string of asterisks according to $word_lengths
    0 讨论(0)
提交回复
热议问题