1

I am currently trying to get my head around some basic php string functions. I currently use this code which determines if the username entered in long enough e.g.:

    if (strlen($_GET['name']) < 3) {
        echo 'First Name should be at least 3 characters long!';
        exit;
    }

And this works just fine. Which string function should I use though if I want to to check on a specific name? E.g. I would like to trigger a message once someone enters a specific Word in the form field.

Some expert advice would be greatly appreciated.

1
  • If you want to trigger a message immediately you should consider using javascript you cannot do that by php without a server roundtrip Commented Jan 16, 2013 at 10:15

5 Answers 5

5

This link of 60 PHP validation functions is an excelent resource.

For your case as to check a name, you could use something like:

if (strtolower($_GET['name']) === 'joe') {
  // Do something for Joe
}

elseif (in_array(strtolower($_GET['name']), array('dave', 'bob', 'jane')) {
  // Do something else for Dave, Bob or Jane
}

The strtolower will ensure that upper, lower or mixed case names will match.

Sign up to request clarification or add additional context in comments.

1 Comment

As @LawrenceCherone mentions, it is always good practice to check that the variable is available with either !empty() or isset() to prevent filling your logs with messages if the variable is not available.
4

You don't need a function for that. You can use a if statement and ==:

if ( $_GET['name'] == 'Dave' )
{
  // user entered 'Dave'
}

Comments

2

if statement, or if you plan to check against multiple names, switch().

switch($_GET['name']){
    case "Eric":
        //Eric
    break;
    case "Sally":
        //Sally
    break;
    case "Tom":
        //Tom
    break;
    default:
        //Unknown
}

Comments

2

Its good practice to check that $_GET['name'] is set before using. To answer your question a good way IMO is in_array(needle,haystack)

<?php 

 if (!empty($_GET['name']) && strlen($_GET['name']) < 3) {
        echo 'First Name should be at least 3 characters long!';
        exit;
 }

 //From a database or preset
 $names = array('Bob','Steve','Grant');
 if(in_array($_GET['name'], $names)){
    echo 'Name is already taken!';
    exit;
 }
?>

Comments

1

You can use strstr or stristr(case-insensitive) function, If want to search for specific word in a sentence.

Just check php mannual for strstr, and stristr.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.