tags:

views:

54

answers:

6
function validText ( $input, $min = null, $max = null )
{   
    if ( !empty($min) && !empty($max) ) {
        $text = "^[a-zA-Z\s0-9]{$min,$max}+$";
    } else {
        $text = "/^[a-zA-Z\s0-9]+$/"; 
    }

    if ( preg_match( $text, $input ) )
    {
        return true;
    }
    else
    {
        return false;
    }
}

whats the problem ? sorry newbie problem

A: 

in PHP double quote strings process escape sequences, so it is probably tripping up on the "\s" inside there. change it to "\s" (to escape the backslash and make it a literal backslash).

Scott M.
+1  A: 

I think php is trying to evaluate your string because you have used double quotes. Try using single quotes instead, and concatenating your variables as needed:

if ( !empty($min) && !empty($max) ) {
    $text = '^[a-zA-Z\s0-9]{' . $min . ',' . $max . '}+$';
} else {
    $text = '/^[a-zA-Z\s0-9]+$/'; 
}

See: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double

Brandon Horsley
+1  A: 

PHP interprets variables in double quoted strings. See String Parsing in the PHP-Documentation. {$min,$max} gets interpreted as the beginning of a variable. And as in PHP , in variablenames are not valid it is unexpected.

To fix your problem Change this line:

$text = "^[a-zA-Z\s0-9]{$min,$max}+$";

To this:

$text = "^[a-zA-Z\s0-9]{" . $min . "," . $max ."}+$";
Benjamin Cremer
A: 

somehow i figure it out :) thanks .

function validText ( $input,$min = null ,$max = null )
{   
    if(!empty($min) && !empty($max)) {
        $text = '^[a-zA-Z\s0-9]{'.$min.','.$max.'}+$';
    } else {
        $text = "/^[a-zA-Z\s0-9]+$/"; 
    }

    if ( preg_match( $text, $input ) )
    {
        return true;
    }
    else
    {
        return false;
    }
}
kaskus
+2  A: 

The problem is in the line:

$text = "^[a-zA-Z\s0-9]{$min,$max}+$";

The problem is that {$var} is a special syntax in PHP. So {$var,$var} is invalid since $var,$var is not a valid variable name...

Try this:

$text = "^[a-zA-Z\s0-9]{{$min},{$max}}+$";
ircmaxell
A: 

The problem is in this line

"^[a-zA-Z\s0-9]{$min,$max}+$"

In strings enclosed in double quotes ("these"), you can include variables like "this = $value".

The clean way to do this, especially when including array elements, is enclosing them using {}, like "This is an array element: {$array['element']}"

Since you have a string containing "{$something, php expects this to be a variable and looks for }, but sees the ,. Hence the error.

This will solve the problem:

"^[a-zA-Z\\s0-9]{{$min},{$max}}+\$"

since the first { will not be interpreted as starting a variable to include.

(yes, the \ and $ are special as well and need to be escaped)

mvds