ProgrammerGirl
ProgrammerGirl

Reputation: 3223

How to check whether StringB starts with StringA in PHP?

How can you check whether StringB starts with StringA if the length of both is variable?

Upvotes: 0

Views: 174

Answers (9)

Ja͢ck
Ja͢ck

Reputation: 173662

The answer has already been accepted, but the following method is - unfortunately due to the nature of php - the only correct one: use strncmp() or ===. Here's why:

Consider the following example input (both strings are equal except for the last number):

$StringA = '9223372036854775808';
$StringB = '9223372036854775807';

Now, we take the following solution:

var_dump(substr($StringB, 0, strlen($StringA)) == $StringA);

Can you guess the return value? It's:

true

Wait, what, why?! Here's why: https://bugs.php.net/bug.php?id=54547

PHP normally gets most of its data from external strings, even if they're numbers. So if your code reads $_POST['key'] == 123 and $_POST['key'] is actually '123', it will still work because PHP will perform a type cast on the string to integer before it calculates the equality.

Same goes for $_GET['key'] == $_POST['key'], assuming both strings have numbers in them. And herein lies the kicker:

PHP determines whether the string(s) look numeric first before comparison. If the numeric value gets too big, however, they overflow into a double and thus lose precision; this causes the comparison to return an unexpected result.

Instead, to compare strings you have to very explicit:

// use strncmp() - the === here is not really necessary btw
var_dump(0 === strncmp($StringB, $StringA, strlen($StringA)));
// use === to perform the comparison in a strict manner
var_dump(substr($StringB, 0, strlen($StringA)) === $StringA);

Returns:

false
false

Normality restored :)

Upvotes: 1

Mihai Stancu
Mihai Stancu

Reputation: 16127

use:

strcmp() / strcasecmp()

It takes into account if lengths are different and only compares until min length.

http://php.net/manual/en/function.strcmp.php

or:

substr_compare()

If you need to compare if StringB starts with StringA and to be certain it's not the other way arround (where StringB would be the shorter one).

http://www.php.net/manual/en/function.substr-compare.php

Both of the above functions are fast and they only iterate through the shortest string once.


As opposed to:

strpos()

Which would attempt to find StringA anywhere in StringB, in order to return the position at which StringA starts.

preg_match

Or other regular expressions which are more expensive operations and should be used for situations where many things need to be checked

Regex engines need to compile the regex string and they employ a lot of backtracking and a lot of looping over the strings to find their matches.

Upvotes: 1

A B
A B

Reputation: 4158

How about something like this?

if (strlen($b) < strlen($a)) {
   //does not match
}

$len = strlen($a);
if (substr($b, 1, $len) == $a) {
   //matches
}

Upvotes: 0

CodeZombie
CodeZombie

Reputation: 5377

In PHP there is no StartsWith() like in other languages. As an alternative, you can use mb_strpos():

if(mb_strpos($source, $start) === 0)

You can create your own StartsWith() function:

function StartsWith($source, $start)
{
    return (mb_strpos($source, $start) === 0);
}

I strongly recommend using the Multibyte String Functions. This way you can work with Unicode strings long before the year 2025 when PHP has full Unicode support ;-).

Upvotes: 3

EmmanuelG
EmmanuelG

Reputation: 1051

You could try:

if(preg_match('/^'.preg_quote($stringA).'.*/', $stringB){ do some stuff }

This will check if B starts with A regardless of string sizes.

EDIT: A good point was brought up. If you want to use preg_match on a string that may have regex special characters in it, use preg_quote($string) to make sure those are escaped before using the string in the regex.

Upvotes: 0

message
message

Reputation: 4603

use strpos for that...

if(strpos($stringB, $stringA) === 0) {
    // starts with stringA
}

Upvotes: 1

StuckAtWork
StuckAtWork

Reputation: 1633

$pos = strpos($StringB, $StringA)

If $pos is 1 or 0 (I forget which) then you know string B starts with string A.

EDIT: It is position 0.

Upvotes: 1

marcelog
marcelog

Reputation: 7180

how about using strpos? (http://php.net/strpos)

if (strpos($stringB, $stringA) === 0) {
    // matched
}

Upvotes: 2

Artefact2
Artefact2

Reputation: 7654

substr($StringB, 0, strlen($StringA)) == $StringA

Upvotes: 2

Related Questions