Confused!
I am trying to extract our localsites' names which are embedded in our WordPress website's structure, ie https://www.website.co.uk/site99/folderX/page. In the URL the localsite name is all lower case without any gaps, whereas the 'display name' of the localsite has a Starting capital and a gap between words. What am I doing wrong here?
if(strpos($_SERVER['REQUEST_URI'], '/site01/') !== false) { $categoryIdOrSlug = 'Site 01';}
elseif (strpos($_SERVER['REQUEST_URI'], '/site02/') !== false) { $categoryIdOrSlug = 'Site 02';}
elseif (strpos($_SERVER['REQUEST_URI'], '/site03/') !== false) { $categoryIdOrSlug = 'Site 03';}
endif;
so what I am looking for is where /site99/ is in position 0 of the slug.
If you are in https://www.website.co.uk/site99/folderX/page
Then : $_SERVER['REQUEST_URI'] will be /site99/folderX/page
if (strpos($_SERVER['REQUEST_URI'], '/site98/') !== false) { $categoryIdOrSlug = 'Site 98';} // strpos($_SERVER['REQUEST_URI'], '/site98/') will be false
elseif (strpos($_SERVER['REQUEST_URI'], '/site99/') !== false) { $categoryIdOrSlug = 'Site 99';} // strpos($_SERVER['REQUEST_URI'], '/site98/') will be 0 (which is success run & is true)
See different outputs:
echo strpos($_SERVER['REQUEST_URI'], '/site99/'); // OUTPUT: 0
Here, strpos() return the index/position at which the 2nd param(/site99/) is present in first param($_SERVER['REQUEST_URI']).
The strpos() function finds the position of the first occurrence of a string inside another string. Related functions: strrpos() - Finds the position of the last occurrence of a string inside another string (case-sensitive)
var_dump(strpos($_SERVER['REQUEST_URI'], '/site98/'));
Output will be bool(false). Why its false because the string was not found in param one. If its found, then the out will be a int of position like int(25).
var_dump(strpos($_SERVER['REQUEST_URI'], '/site99/'));
Output will be int(0) because strpos() has successfully found /site99/ in $_SERVER['REQUEST_URI'].
And, normally === or !== are used for Boolean value(TRUE/FALSE) comparisons.
No need to get confused with strpos() and !== both are entirely different, one returns a position index value(if found) or FALSE, if not found required string. Whereas, !== compares left & right side values of operator & says TRUE or FALSE.
Reply to your comment:
Yes, you are getting correct answer. As you said to making ensure we are using if() check.
You see we are getting int(0) while var_dump(strpos($_SERVER['REQUEST_URI'], '/site99/'));. If we have a index value(even its 0) its treated as a success run(true). That is, the string you are searching is found in index 0 or at a particular position of $_SERVER['REQUEST_URI']. if() makes sure that the check is correct, int(0) !== false means int(0) is a success run(which is also said as true). So if(int(0) !== false) can be said also as if(true !== false) which is true & so $categoryIdOrSlug = 'Site 99'; will run.
if() can also be written as:
if (strpos($_SERVER['REQUEST_URI'], '/site98/')) { $categoryIdOrSlug = 'Site 98';}
elseif (strpos($_SERVER['REQUEST_URI'], '/site99/')) { $categoryIdOrSlug = 'Site 99';}
echo $categoryIdOrSlug; // output: Site 99
You cant check by === 0 because we cant say the position at which strpos() founds the searching string, it may vary.
Related
Good day,
I have the following string :
[Star]ALERT[Star]Domoos detects blabla[blabli]
For strange reasons, the code below does not detect the star at the very first character. I read in the php documentation that the first character has an index of 0. However, if I am looking for the '[', the function works very well.
What I am trying to achieve is to ensure that the first character of my string is really a * (star). Strangely, if I enter $pos1 = strpos($inputString, '*', 1), the star shown at position '6' would be returned.
I don't quite understand why my code does not work as expected (i.e. does not enter into the 'true' condition)
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$pos1 = strpos($inputString, '*', 0);
if ($pos1 == True)
{
echo 'position' . $pos1;
}
Do you have any suggestion that would help me to overcome this issue?
Thanks a lot for your appreciated support.
change condition to
if ($pos1 != False)
{
echo 'position' . $pos1;
}
as strpos will return position at (integer) or False
If you look at the manual:
Find the numeric position of the first occurrence of needle in the
haystack string.
In your test case, the numeric position is 0 and 0 != true.
Also see the warning in the manual:
Warning This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
So the condition you really want is:
if ($pos1 !== false)
You don't need strpos. As string is an array of characters so you can do like this
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$compare_char= $inputString[0];
if($compare_char=="*"){
//do something.
}
As i suppose it is fast too rather than on searching through strpos
Actually issue is that when you are looking at 0 position the value which you get is 0 and when you are checking that in if condition with True, it will always fail because 0 will be evaluated as False. To resolve this you can use
if($pos1 !== False)
The function strpos returns false if there is no existence of what you search. So make a check like the following:
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$pos1 = strpos($inputString, '*', 0);
return $pos1 !== false ? 'position ' . $pos1 : '..';
$pos1 returns 0 and this is treat as False so we cant take it as True so we can use here isset function.
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$pos1 = strpos($inputString, '*',0);
if (isset($pos1))
{
echo 'position' . $pos1;
}
Ok, I am trying to do an IF / else IF statement that doesn't act as i would expect.
I am trying to check that a URL address someone enters for certain things.
The way I have done it is probably crap but I am not that good at programming.
All the IF parts work except for this bit if (strpos($URLcheck, "http://") == false)
It is supposed to check if the URL has http:// in it. But whether it does or doesn't it still acts exactly the same way.
I even tried forcing the http:// into the URL by stripping it of http:// or https://.
When I echo the variable ($URLcheck) , it shows the URL with the http://.....so why doesn't my code work?
Thanks
$URL = htmlspecialchars($_POST["URL"]);
$URLREMOVESarray = array('https//:', 'http//:');
$URLhttp = str_replace($URLREMOVESarray, "", $URL);
$URLcheck = "http://" . $URLhttp;
$URLsearchcheck2 = 'property-profile/';
$URLsearchcheckDomain = "domain";
if (strpos($URL, $URLsearchcheck2) !== false) {
echo "Test 1";
}
else if (strpos($URLcheck, "http://") == false) {
echo "Test 2";
echo $URLcheck;
}
else if (strpos($URLcheck, $URLsearchcheckDomain) == false) {
echo "Test 3";
}
else if (strpos($URLcheck, $URLsearchcheckDomain) == true) {
Continue1();
}
Update: Still no solutions to why this doesn't work? I have even copy and pasted the code from this page and it still doesn't work.
use the same !== false statement:
$URLcheck = 'http://www.google.com';
if (strpos($URLcheck, "http://") !== false) {
echo "Test 2";
echo $URLcheck;
}
strpos($URLcheck, "http://") searches for "http://" in the $URLcheck string and returns its position if it's found. In your case, it is indeed found at position 0 (start of $URLcheck string).
If strpos() doesn't find what it's looking for, it returns a false, which is not the same as 0, even though it sometimes seems so in PHP. This is the source of confusion for many less-experienced php devs, I advise to at least take a look at http://php.net/manual/en/types.comparisons.php
Anyway, in your case, the 0 that strpos returns is then checked if it equals false (with ==). But since 0 is an integer type and false is a boolean type, PHP has to convert the 0 to boolean and the best match for zero between true and false is obviously false. That's why your if statement behaves as it does, it's actually perfectly correct behaviour.
So what you need to do is check whether your strpos() output is identical to false instead of whether it equals it. You do this by simply adding another = to your condition, so it reads strpos($URLcheck, "http://") == false.
ok, nothing worked that I tried from the suggestions so I went with this code and it works. No idea why the other code wouldn't work
$pos = strpos($URLhttp, 'example.com');
if ($pos === false) {
echo "Test 1";
}
Im trying to get something to be echoed if the user is on one of the two pages, but it isn't echoed
if(stripos($_SERVER['REQUEST_URI'], 'user.php') || ($_SERVER['REQUEST_URI'], 'message.php')) {
echo 'hello';
}
First of all, $_SERVER['REQUEST_URI'] will give you the URI which was given in order to access this page, not the actual page name. Use basename($_SERVER['PHP_SELF']) to get the actual page name.
And second, the condition of your if clause is also wrong. From the manual of stripos() function:
Returns the position of where the needle exists relative to the beginnning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
So both of your conditions will fails if the needle matches exactly with the haystack. Instead check the condition like this:
if(stripos($haystack, $needle) !== false || stripos(stripos($haystack, $needle)) !== false) {
echo 'hello';
}
So the solution is like this:
if(stripos(basename($_SERVER['PHP_SELF']), 'user.php') !== false || stripos(basename($_SERVER['PHP_SELF']), 'message.php') !== false) {
echo 'hello';
}
if(stripos($_SERVER['REQUEST_URI'], 'user.php') || stripos($_SERVER['REQUEST_URI'], 'message.php')) {
echo 'hello';
}
Notice the stripos function in the clause after ||.
Wrap each conditional argument in its own block with parenthesis. Every function added to the condition must include 2 parenthesis.
IF ( ($a == $x) or ($b == $y) ) {}
if (
(stripos($_SERVER['REQUEST_URI'], 'user.php')) ||
(stripos($_SERVER['REQUEST_URI'], 'message.php'))
) {
echo 'hello';
}
I know the $a variable with the tag is not properly formatted, however that's irrelevant to the issue.
The issue is that strpos is looking for a forward slash, /, in the value of each key in the array, but it is not printing.
$a = '<a target="" href="/test/url">test';
$a_expanded = explode("\"", $a);
echo print_r($a_expanded);
foreach($a_expanded as $num => $aspect) {
echo $aspect;
if ($contains_path = strpos($aspect, '/')) {
echo $a_expanded[$num];
}
}
It echos the array and each aspect, but will not echo the string with the forward slashes when found by strpos.
if ($contains_path = strpos($aspect, '/'))
should be
$contains_path = strpos($aspect, '/');
if ($contains_path !== false)
as strpos will return 0 when the string directly starts with a / (as it does, in your case). If strpos has no match, it returns false.
if (0) and if (false) are the same. So you need to do strict comparison (=== or !==) here.
The position of found string might be 0 which is counted as false, you need to compare as ===
if (false !== $contains_path = strpos($aspect, '/')) {
echo $a_expanded[$num];
}
strpos() could either return FALSE, 0, or a non-zero value.
If the needle occurs at the beginning of the haystack, strpos() returns 0.
If it occurs elsewhere, it returns the respective position of the needle in the haystack.
If needle wasn't found in the haystack, strpos() returns boolean FALSE.
I wasn't checking for strict equality, so the if statement always returned a falsey value, causing my code to not work.
if ($contains_path = strpos($aspect, '/'))
To fix the issue, you could use !==, which compares the type and value:
if ($contains_path = (strpos($aspect, '/') !== FALSE))
For more information, check the following links:
http://php.net/strpos
http://www.php.net/manual/en/language.operators.comparison.php
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!";
}