simple strpos() not working with "[" char, why? - php

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';
}

Related

Filter specific column in array in php

I am trying to filter a specific column in an array in php using the code below:
(strpos( 'meeting',$event['categories'] ) == false )
It is not working actually. An example of what [categories] hold is:
$event['categories'] = 'meeting;skype'
Thanks in advance!
You need to flip the arguments to strpos():
if (strpos($event['categories'], 'meeting') === false) {
echo $event['categories'] . ' does not contain "meeting"';
}
Also, use strict comparison (=== vs ==), as meeting could be at the start of the string, and then strpos() would return 0, which would evaluate to false (which would be wrong in that case).
For reference, see:
http://php.net/manual/en/function.strpos.php
For an example, see:
https://3v4l.org/Ab4ud
I think you should use === not == and also flip the arguments
(strpos($event['categories'] , 'meeting') === false )
strpos could return 0 or false and when you use == then zero is like false
see compression operators
see strpos() docs
<?php
$event = ['categories' => 'meeting;skype'];
$needle = 'meeting';
$haystack = $event['categories'];
if( ($pos = strpos( $haystack, $needle )) === false){
echo "\n$needle not found in $haystack";
}
else
{
echo "\n$needle exists at position $pos in $haystack";
}
See demo
The two things to watch out for are the order of the parameters for strpos() as well as doing a strict comparison using the identity operator ("===") so that when the 'needle' appears at position zero of the 'haystack' it's not mistakenly deemed a false result which occurs if you use the equality operator ("=="), given that in PHP zero == false.

Unable to get the position of a character within my string using strpos

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;
}

strpos() not working as expected?

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

strpos not working as expected, what am i doing wrong?

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)

strpos not finding one word in a string

In the following code, if I set $what to 'red', it doesn't find it, whereas it finds green and blue. Why and how to make it find red as well?
$where = 'red,green,blue';
$what = 'blue';
if (strpos($where, $what) == true) {
echo 'found';
}
strpos returns the index of the found string. In this case the index is 0 and your check for == true will fail. Try:
strpos($where, $what) !== false
The documentation provides more information.
strpos will return false if your string isn't there. Otherwise, it returns the position of your string.
In this case, 'red' 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, 'red') === false)

Categories