Blondie
Blondie

Reputation: 59

Compare first 4 characters of a string PHP

The problem is with this line:

if $var LIKE '1800%';

and I'm not sure how to fix it. Thanks.

<?php 
//check to see if account number is like 1800*
if (isset($_POST['acct_number'])) {
$var = $_POST['acct_number'];
    if $var LIKE '1800%'; {
        //stop the code
        exit;
    } else {
        echo 'normal account number';
    }
}
?>

Upvotes: 0

Views: 1765

Answers (4)

Ismael Moral
Ismael Moral

Reputation: 732

I would use a regular expression for this preg_match('/^1800.+/', $search, $matches);

Upvotes: 1

Ambrish Pathak
Ambrish Pathak

Reputation: 3968

Another way could be to use strpos()

if (strpos($var, '1800') === 0) {
   // var starts with '1800'
}

Upvotes: 3

AbraCadaver
AbraCadaver

Reputation: 79024

You need PHP not MySQL. For 1800% just check that it is found at position 0:

if(strpos($var, '1800') === 0) {
    //stop the code
    exit;
} else {
    echo 'normal account number';
}

If it can occur anywhere like %1800% then:

if(strpos($var, '1800') !== false) {
    //stop the code
    exit;
} else {
    echo 'normal account number';
}

Upvotes: 1

Dark Knight
Dark Knight

Reputation: 6541

Use substr function to get first 4 characters and compare it with 1800.

if(substr($var, 0, 4) == '1800')
{
 // your code goes here.
}
``

Upvotes: 2

Related Questions