Porto

Test For Prime Numbers With PHP Regular Expression

Test For Prime Numbers With PHP Regular Expression

Here is a simple little trick to check if a number is prime using regular expressions. This function builds a string of 1's and repeats them for the length of the number and test agains that string.

An issue arrises with the pcre.backtrack_limit setting in php.ini which is set to 100000 by default, so that the number 22201 will return as being prime. By adjust this lime 20 200000 the issue goes away. You may wish to check for this error in your code using the following.

if ( preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR )

<?php

/**
* Test if a number is prime using regular expression
*
* @param    int    $number
* @return    bool
*
*/
function is_prime$number )
{
    
$str str_repeat("1"$number);
    if( 
preg_match'/^1?$|^(11+?)\1+$/'$str ) == )
    {
        return 
true;
    }
    return 
false;
}

    
$numbers = array( 123452137 );

    foreach( 
$numbers as $num )
    {
        if( 
is_prime$num ) ==  false)
        {
            echo 
"$num is not prime \n";
        }
        else
        {
            echo 
"$num is prime \n";
        }
    }
?>

Demonstration

1 is not prime
2 is prime
3 is prime
4 is not prime
5 is prime
21 is not prime
37 is prime