I have a string in $str variable.
How can I verify if it starts with some word?
Example:
$str = "http://somesite.com/somefolder/somefile.php";
When I wrote the following script returns yes
if(strpos($str, "http://") == '0') echo "yes";
BUT it returns yes even when I wrote
if(strpos($str, "other word here") == '0') echo "yes";
I think strpos returns zero if it can't find substring too (or a value that evaluates to zero).
So, what can I do if I want to verify if word is in the start of string? Maybe I must use === in this case?
You need to do:
if (strpos($str, "http://") === 0) echo "yes"
The === operator is a strict comparison that doesn't coerce types. If you use == then false, an empty string, null, 0, an empty array and a few other things will be equivalent.
See Type Juggling.
You should check with the identity operator (===), see the documentation.
Your test becomes:
if (strpos($str, 'http://') === 0) echo 'yes';
As #Samuel Gfeller pointed out: As of PHP8 you can use the str_starts_with() method. You can use it like this:
if (str_starts_with($str, 'http://')) echo 'yes';
PHP does have 2 functions to verify if a string starts with a given substring:
strncmp (case sensitive);
strncasecmp (case insensitive);
So if you want to test only http (and not https), you can use:
if (strncasecmp($str,'http://',7) == 0) echo "we have a winner"
check with
if(strpos($str, "http://") === 0) echo "yes";
as == will turn positive for both false & 0 check the documentation
Another option is:
if (preg_match("|^(https?:)?\/\/|i", $str)) {
echo "the url starts with http or https upper or lower case or just //.";
}
As shown here: http://net.tutsplus.com/tutorials/other/8-regular-expressions-you-should-know/
strncmp($str, $word, strlen($word))===0
Is a bit more performant than strpos
Starting with PHP 8 (2020-11-24), you can use str_starts_with:
if (str_starts_with($str, 'http://')) {
echo 'yes';
}
PHP 8 has now a dedicated function str_starts_with for this.
if (str_starts_with($str, 'http://')) {
echo 'yes';
}
if(substr($str, 0, 7)=="http://") {
echo("Statrs with http://");
}
There's a big red warning in the documentation about this:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
strpos may return 0 or false. 0 is equal to false (0 == false). It is not identical to false however, which you can test with 0 === false. So the correct test is if (strpos(...) === 0).
Be sure to read up on the difference, it's important: http://php.net/manual/en/language.operators.comparison.php
Related
if(strpos("http://www.example.com","http://www.")==0){ // do work}
I'd expect this to resolve as true, which it does. But what happens when I do
if(strpos("abcdefghijklmnop","http://www.")==0){// do work}
This also passes on php 5 because as far as I can work out the strpos returns false which translates as 0.
Is this correct thinking/behaviour? If so what is the workaround for testing for that a substring is at the beginning of another string?
Yes, this is correct / expected behavior :
strpos can return 0 when there is a match at the beginning of the string
and it will return false when there is no match
The thing is you should not use == to compare 0 and false ; you should use ===, like this :
if(strpos("abcdefghijklmnop","http://www.") === 0) {
}
Or :
if(strpos("abcdefghijklmnop","http://www.") === false) {
}
For more informations, see Comparison Operators :
$a == $b will be TRUE if $a is equal to $b.
$a === $b will be TRUE if $a is equal to $b, and they are of the same type.
And, quoting the manual page of strpos :
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please
read the section on Booleans for
more information. Use the ===
operator for testing the return
value of this function.
=== and !== compare type and value as shown below:
if (strpos("abcdefghijklmnop", "http://www.") !== false) {
// do work
}
strpos returns an int or boolean false. the == operator also evaluates 0 to mean false, you want to use the === operator (three equals signs) that also checks that the types being compared are the same instead of just seeing if they can be evaluated to mean the same.
so
if (strpos($hastack, $needle) === 0)
{
// the $needle is found at position 0 in the $haystack
}
0 is a possible return value from strpos when it finds a match at the very beginning. In case if the match is not found it returns false(boolean). So you need to check the return value of strpos using the === operator which check the value and the type rather than using == which just checks value.
I personally tend to use this way :
if(!strpos($v,'ttp:'))$v='http://'.$v;
or
if(strpos(' '.$v,'http'))
to avoid the "0" position then always make it a number more than 0
cheers
I'm trying to do some validation in PHP, and one of them is checking whether there is a specific word in the inputted string or not.
The problem is, my code seem to not working when I put the specified word first.
here's the code:
$word = "aa bb cc dd";
if(strpos($word, 'aa') == false)
{
echo "wrong input";
}
but if I change the $word to either bb aa cc dd or bb cc dd aa, it works. I wonder how to fix this though.
strpos will return false if your string isn't there. Otherwise, it returns the position of your string.
In this case, 'aa' is at the start of the string, which means that it's at position 0; and 0 evaluates to false.
You need to do a boolean compare on the result:
if(strpos($word, 'aa') === false)
That's because strpos returns the position of the word, in this case 0. 0 is falsey. == does not check for identical matches, === does. So use a triple equals.
It's even in the docs.
strpos is returning 0, as 'aa' is the 0th character. As 0 == false but does NOT === false (it is not boolean), you need to use === instead of ==.
You should use the strict comparison operator, this will match against the same type, so using === will check if it's a Boolean:
if(strpos($word, 'aa') === false)
{
echo "wrong input";
}
Using == is a loose comparison, anything can be stated true (apart from true, 1, string), e.g.
"false" == false // true
"false" === false // false
The reason why it's false because it's comparing a string against a Boolean which returns false.
Because the position of aa is 0, which equals to false.
You have to use:
if(strpos($word, 'aa') === false)
Add a space before search string and find more than 0 position
if(strpos(" ".$word, 'aa') > 0)
{
echo "Found it!";
}
if (strrpos($_POST['security_data'], $OrderReference) === false ||
md5($_POST['security_data'] . $sekey) != $_POST['security_hash'])
{
return;
}
I don't understand why is strrpos in there and === "3 equals"
and what is the dot "." doing in $_POST['security_data'] . $sekey
Thank You
strrpos returns the position of the substring.
echo strrpos("Hello", "e"); // outputs `1`
. is concatenation.
echo "Hello "."There"; // outputs: 'Hello There'
=== checks type as well as equality.
var_dump(1 == true); // true
var_dump(1 === true); // false
Here's a translation to C#:
string hash = MD5.Create().ComputeHash(Request.Form["security_data"] + sekey);
if (!Request.Form["security_data"].Contains(OrderReference)
|| hash != Request.Form["security_hash"])
{
return;
}
strrpos returns false if the string isn't found (don't know which string in which, but the docs will tell you)
=== compares type as well instead of just value. This is done so php doesn't to any casting, for example 0 == false (0 represents false in php as well) but 0 !== false as 0 isn't the same type as false.
the . is the concat operator in php.
strrpos is "return position of substring within a string, starting from the right (end) side". === is the PHP strict comparison, which compares type AND value. The strpos functions CAN return a legitimate 0 as a position, which is the very start of the string. But 0 evalutes to boolean FALSE in PHP, so the === check ensures that you're looing at a real false (strrpos found nothing) and not just "strrpos found string at position zero".
The dot (.) connects between 2 strings, and the 3 equals checks if the returned value is in the same type as what it compared to
If the contents of the variable $OrderReference are not found in the POST variable security_data, or the MD5 hash of the POST variable security_data, concatenated with (that's the . operator in PHP) the variable $sekey isn't equal to security_hash, return from the function.
=== is used to ensure that the return from strrpos() is the boolean FALSE rather than the possible valid return value of 0. === is for strict type comparison.
<?php
if(stripos('http://cp.uctorrent.com', 'cp.utorrent.com') >= 0){
echo "Good1";
}else{
echo "Bad1";
}
if(stripos('http://uctorrent.com', 'cp.utorrent.com') >= 0){
echo "Good2";
}else{
echo "Bad2";
}
?>
output is
Good1Good2
whereas it should be
Good1Bad2
<?php
if(false >= 0) echo "Good";
else echo "Bad";
// this code prints Good
?>
It's not a bug, it's a "weird" boolean conversion.
stripos returns false when the string is not found, and false converts to 0 in PHP.
Directly from the documentation (the problem is the other way around) :
Warning This function may return
Boolean FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator for
testing the return value of this
function.
In case 2 stripos returns false as the search fails and false when compared with 0 returns true.
The right way of doing it is to use the identity operator which checks both type and value:
if(stripos('http://cp.uctorrent.com','cp.utorrent.com') !== false)
echo "Good1"; ^^^^^^^^^^
else
echo "Bad1";
Reading the manual would help greatly:
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
If needle is not found, stripos() will return boolean FALSE.
http://php.net/manual/en/function.stripos.php
Boolean FALSE in PHP is equivalent to integer 0, which is >= 0.
If you want to check whether stripos failed to get a match, you need to test for type and value with !== or ===, for example:
<?php
if(stripos('http://cp.uctorrent.com','cp.utorrent.com')!==false)echo "Good1";
else echo "Bad1";
if(stripos('http://uctorrent.com','cp.utorrent.com')!==false)echo "Good2";
else echo "Bad2";
?>
Again, try this and avoid the issues caused by microoptimization function use patterns:
if (stristr('http://cp.uctorrent.com', 'cp.utorrent.com')) {
echo "Good1";
}
else {
echo "Bad1";
}
Below $p has value 'false' (means 0), so it's >=0
$p = stripos('http://uctorrent.com','cp.utorrent.com');
You need to check stripos('http://uctorrent.com','cp.utorrent.com') !== false first then get $p (found position) like above...
utorrent <---> uctorrent
i am such an idiot...
it was spell mistake ...
comparing uctorrent with utorrent
sorry every one
if(strpos("http://www.example.com","http://www.")==0){ // do work}
I'd expect this to resolve as true, which it does. But what happens when I do
if(strpos("abcdefghijklmnop","http://www.")==0){// do work}
This also passes on php 5 because as far as I can work out the strpos returns false which translates as 0.
Is this correct thinking/behaviour? If so what is the workaround for testing for that a substring is at the beginning of another string?
Yes, this is correct / expected behavior :
strpos can return 0 when there is a match at the beginning of the string
and it will return false when there is no match
The thing is you should not use == to compare 0 and false ; you should use ===, like this :
if(strpos("abcdefghijklmnop","http://www.") === 0) {
}
Or :
if(strpos("abcdefghijklmnop","http://www.") === false) {
}
For more informations, see Comparison Operators :
$a == $b will be TRUE if $a is equal to $b.
$a === $b will be TRUE if $a is equal to $b, and they are of the same type.
And, quoting the manual page of strpos :
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please
read the section on Booleans for
more information. Use the ===
operator for testing the return
value of this function.
=== and !== compare type and value as shown below:
if (strpos("abcdefghijklmnop", "http://www.") !== false) {
// do work
}
strpos returns an int or boolean false. the == operator also evaluates 0 to mean false, you want to use the === operator (three equals signs) that also checks that the types being compared are the same instead of just seeing if they can be evaluated to mean the same.
so
if (strpos($hastack, $needle) === 0)
{
// the $needle is found at position 0 in the $haystack
}
0 is a possible return value from strpos when it finds a match at the very beginning. In case if the match is not found it returns false(boolean). So you need to check the return value of strpos using the === operator which check the value and the type rather than using == which just checks value.
I personally tend to use this way :
if(!strpos($v,'ttp:'))$v='http://'.$v;
or
if(strpos(' '.$v,'http'))
to avoid the "0" position then always make it a number more than 0
cheers