PHP Detect Duplicate Text

后端 未结 9 1381
夕颜
夕颜 2021-02-05 07:52

I have a site where users can put in a description about themselves.

Most users write something appropriate but some just copy/paste the same text a number of times (to

9条回答
  •  终归单人心
    2021-02-05 08:22

    // 3 examples of how you might detect repeating user input
    
    // use preg_match
    
    // pattern to match agains
    $pattern = '/^text goes here$/';
    
    // the user input
    $input = 'text goes here';
    
    // check if its match
    $repeats = preg_match($pattern, $input);
    
    if ($repeats) {
        var_dump($repeats);
    } else {
        // do something else
    }
    
    // use strpos
    
    $string = 'text goes here';
    $input = 'text goes here';
    $repeats = strpos($string, $input);
    
    if ($repeats !== false) {
        # code...
        var_dump($repeats);
    } else {
        // do something else
    }
    
    // or you could do something like:
    function repeatingWords($str)
    {
        $words = explode(' ', trim($str));  //Trim to prevent any extra blank
        if (count(array_unique($words)) == count($words)) {
            return true; //Same amount of words
        }
    
        return false;
    }
    
    $string = 'text goes here. text goes here. ';
    
    if (repeatingWords($string)) {
        var_dump($string);
    } else {
        // do something else
    }
    

提交回复
热议问题