Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,850 questions

51,771 answers

573 users

How to validate a string in PHP

3 Answers

0 votes
// The rules depend on your needs

function validateString($string, $minLength = 1, $maxLength = 255, $pattern = "/^[a-zA-Z0-9\s]+$/") {
    // Check length
    if (strlen($string) < $minLength || strlen($string) > $maxLength) {
        return false;
    }
    
    // Check pattern
    if (!preg_match($pattern, $string)) {
        return false;
    }
    
    return true;
}

$str = "PHP Programming";
if (validateString($str, 6, 55)) {
    echo "Valid string!";
} else {
    echo "Invalid string!";
}




/*
run:

Valid string!

*/

 



answered Apr 13, 2025 by avibootz
edited Apr 13, 2025 by avibootz
0 votes
// The rules depend on your needs

function validateString($string, $rules = []) {
    // Default rules
    $defaultRules = [
        'minLength' => 1,
        'maxLength' => 255,
        'pattern' => "/^[a-zA-Z0-9\s]+$/"
    ];
    
    // Merge default rules with custom rules
    $rules = array_merge($defaultRules, $rules);
    
    // Check length
    if (strlen($string) < $rules['minLength'] || strlen($string) > $rules['maxLength']) {
        return false;
    }
    
    // Check pattern
    if (!preg_match($rules['pattern'], $string)) {
        return false;
    }
    
    return true;
}

$str = "PHP Programming";
$customRules = [
    'minLength' => 6,
    'maxLength' => 55,
    'pattern' => "/^[a-zA-Z\s]+$/"
];

if (validateString($str, $customRules)) {
    echo "Valid string!";
} else {
    echo "Invalid string!";
}



/*
run:

Valid string!

*/

 



answered Apr 13, 2025 by avibootz
0 votes
// The rules depend on your needs

function validateString($string, $callbacks = []) {
    foreach ($callbacks as $callback) {
        if (!call_user_func($callback, $string)) {
            return false;
        }
    }
    return true;
}

// Custom validation functions
function checkLength($string) {
    return strlen($string) >= 6 && strlen($string) <= 55;
}

function checkPattern($string) {
    return preg_match("/^[a-zA-Z\s]+$/", $string);
}

$str = "PHP Programming";
$callbacks = ['checkLength', 'checkPattern'];

if (validateString($str, $callbacks)) {
    echo "Valid string!";
} else {
    echo "Invalid string!";
}



/*
run:

Valid string!

*/

 



answered Apr 13, 2025 by avibootz
...