I was attempting to follow the example on php.net for strpos() but it does not seem to be working as expected for me. It keeps printing the else case "not here".
$href = "[!--\$testUrl('testlink','754')--]";
dpm($href);
$search_wcm = 'testUrl';
$pos_wcm = strpos($search_wcm, $href);
if ($pos_wcm !== false) {
dpm('here');
} else {
dpm('not here');
}
Note: dpm is a Drupal function that simply displays information in the messages region of a Drupal site. Think of it as an 'echo' or 'print' with styling attached to it.
Wrong order, the first param should be the string to search in
$pos_wcm = strpos($href, $search_wcm);
From the manual you have your arguments backwards:
http://us2.php.net/manual/en/function.strpos.php
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
strpos($href,$search_wcm)
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;
}
I am working on a project and a part of it requires to validate name fields.
Here is the logic:
If any name value contains an 'i' after 'e' that is not after 'c',
then issue an error.
I know I should try to write something and then share it, but in this case I have no idea how its done. I know preg_match() can be a solution , but again I have no idea how its done.
I know I will get down vote due to not writing anything, but hopefully I get an answer.
Thanks Guys,
You can use stripos() (or strpos() if case sensitivity is required). To demonstrate:
$str1 = "weird";
$str2 = "ceiling";
checkCEI($str1); // Echoes "Error for weird"
checkCEI($str2); // output true, as it passes the test
function checkCEI($str) {
if (stripos($str, "ei") !== false && stripos($str, "cei") === false) {
return "Error for ".$str;
}
return true;
}
You should use preg_match() as you say.
Here it is your pattern:
[^c]ei - for all strings, where there is NO C berfore EI
$badString = 'ceiling';
$goodString = 'vein';
$pattern = '/[^c]ei/';
preg_match($pattern,$badString); // 0
preg_match($pattern,$goodString); //1
If you want all strings that match with 'cei', you don't need regex.
You can use stripos
$goodString = 'ceiling';
$badString = 'vein';
stripos($badString, 'cei'); // -1
preg_match($goodString,'cei'); //1
Important! Please check manual for returning values of both functions.
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";
}
why does if i do:
if(strpos("[","[rgeger]")){
echo 'hey';
}
it doesn't prints anything?
try this with a string:
function return_tags($keywords){
if($keywords){
$k_array = array();
foreach($this->check($keywords) as $key=>$value){
array_push($k_array, $value);
}
$last_array = array();
foreach($k_array as $key=>$value){
if(strpos("[", $value) && strpos("]", $value) && strlen($value) >= 2){
$value = '<span class="tag">'.$value.'</span>';
}
array_push($last_array, trim($value));
}
return $last_array;
}else{
return false;
}
}
string example
$keywords = "freignferi eiejrngirj erjgnrit [llll] [print me as tag]";
did you see any <span> element printed in html?
It looks like you swapped the arguments:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
So if you want to know if a [ is in your string [rgeger]:
if (strpos("[rgeger]", "[") !== false) {
echo 'hey';
}
(Source: http://php.net/strpos)
The position returned is zero-indexed, so the first character is at position 0. When evaluating 0 as Boolean, it's false - so it doesn't get into the block.
Fix with this:
if (strpos('[rgeger]', '[') !== false)
Also the arguments are the wrong way round. Don't upvote this post any more; go upvote robbi's instead for spotting that one :) Eagle eyes robbi, EAGLE eyes :P
Because you have to check the return value of strpos() as it could be zero because [ it's at index zero, and zero evaluates to FALSE that's why it wouldn't enter your if block, so check that the return value it's FALSE and type boolean, not just integer zero, like this:
if(strpos("[rgeger]","[") !== false){
echo 'hey';
}
UPDATE:
The parameters were in wrong order too, the subject string comes first then the search string, I updated my code above to reflect that.
Because its wrong. Strpos give false if the condition is false.
if(strpos("[rgeger]","[") !== false){
echo 'hey';
}
Edit: I have corrected my answer. Your parameter are in the wrong order. Its:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
Because actually strpos can return 0 see doc.
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 you have to compare with the falsevalue directly.
if(strpos("[","[rgeger]") !== false){
echo 'hey';
}
EDIT ::
Careful.. Look at the arguments order
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
Haystack is the string input.
Needle is what you are seeking for.
if(strpos("[regeger]","[") !== false){
echo 'hey';
}
I need to execute a bit of script only if the $_GET['page'] parameter has the text "mytext-"
Querystring is: admin.php?page=mytext-option
This is returning 0:
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
echo $match;
strpos returns the position of the string. Since it's 0, that means it was found at position 0, meaning, at the start of the string.
To make an easy way to understand if it's there, add the boolean === to an if statement like this:
<?php
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
if ( $match === false ) {
echo 'Not found';
} else {
echo 'Found';
}
?>
This will let you know, if the string is present or not.
Or, if you just need to know, if it's there:
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
if ( $match !== false ) {
echo 'Found';
}
?>
Use substr() once you get the location of 'mytext-', like so:
$match = substr($myPage, strpos( $myPage, 'mytext-') + strlen( 'mytext-'));
Otherwise, strpos() will just return the numerical index of where 'mytext-' starts in the string.
You can also use str_replace() to accomplish this if your string only has 'mytext-' once:
$match = str_replace( 'mytext-', '', $myPage);
The function strpos() returns the position where the searched string starts which is 0. If the string is not found, the function will return false. See the strpos documentation which tells you as well:
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.
A solution to your question would be to use substr(), preg_match() or check if strpos() !== false.
The easiest solution should be this:
if (preg_match('/^mytext-/i', $_GET['page'])) {
// do something
}
You may also consider using more than just one GET parameter like
http://www.example.com/foo.php?page=mysite&option1=123&option2=456
You then use your parameters lik $_GET['page'], $_GET['option1'], $_GET['option2'], etc.
However, you should also be careful what you do with raw $_GETor $_POST data since users can directly input them and may inject harmful code to your website.
That is expected since the substring starts at index 0. Read the warning on php.net/strpos:
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.
If you only need to check if $myPage contains 'mytext-', use stristr:
if(stristr($myPage, 'mytext-') !== false) {
// contains..
}
What's wrong about preg_match?
$myPage = $_GET['page'];
if (preg_match("/\bmytext-\b/i", $myPage)) {
//Do Something
}
Or do you need the "option" out of "mytext-option"?
If yes you can use this:
$myPage = $_GET['page'];
$querystrings = explode("-", $myPage);
if ($querystrings[0] == 'mytext')) {
//Do Something
echo $querystrings[1]; //outputs option
}
With this you can even use more "options" in your querystring like "mytext-option-whatever". That's the same as when you use
$_GET['page'], $_GET['option'], $_GET['whatever']
when you use
?page=mysite&option=x&whatever=y