Using strpos to check the existence of substring - php

I am trying to exclude those tweets which are not having RT # in their text.
Here is my code:
foreach ($tweets3 as $item)
{
$text = $item->text;
$check = 'RT #';
$result = strpos($text, $check);
if($result == false)
continue;
}
But these tweets also get excluded
Mention text : RT #IBMcloud: A few #cloud highlights from the #IBM Annual Report. Read more: http://t.co/TJBHoX3vdU http://t.co/fG66SE7kV1
RT #holgermu: MyPOV - Nice way to put out our annual report in an interactive (engaging?) format - here is #IBM's - http://t.co/TIqi0soc5W
RT #TopixPolitix: Chinese State and Citizens Must Battle Airpocalypse Together http://t.co/nV5TGJG6Fl - http://t.co/cln83ufDnk
Though they have RT # in their text. Why?

See this warning in the documentation for strpos():
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Use the === operator for testing the return value of this function.
As the documentation says, strpos() can return values that evaluate to boolean FALSE. For example, strpos() will return 0 if there is a match at the beginning of the string.
To avoid ambiguity, always use strict comparison (===) instead of loose comparison (==) (whenever possible):
foreach ($tweets3 as $item)
{
$text = $item->text;
$check = 'RT #';
$result = strpos($text, $check);
// if "RT #" text not found in tweet, skip to next iteration
if ($result === false) continue;
}

I think your logic is flipped. $result will hold the numerical value if the text is found. You want your check to be:
if($result !== false)
continue;

Related

Why the array_search not matching? [duplicate]

This question already has answers here:
php array_search returning 0 for the first element?
(4 answers)
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
(13 answers)
Closed 5 years ago.
Why does example A fail, but example B work?
A) FAIL:
$request_IP = '8.8.8.8';
$list_Array = explode(',', "8.8.8.8,9.9.9.9,2.2.2.2");
$result = array_search($request_IP, $list_Array);
if($result) {
// Expecting - to get it success there
}
else {
echo "FAIL";
exit;
}
B) WORKS:
$request_IP = '8.8.8.8';
$list_Array = explode(',', "0,8.8.8.8,9.9.9.9,2.2.2.2");
$result = array_search($request_IP, $list_Array);
if($result) {
// In this case it works??
}
else {
echo "FAIL";
exit;
}
From the documentation for array_search:
Returns the key for needle if it is found in the array, FALSE otherwise.
So you should change your code to:
$result = array_search($request_IP, $list_Array);
if ($result === false) {
// Not found
echo "FAIL";
exit;
} else {
// $result is the key of the element in the array
echo $result . "\n";
}
Example A matches properly, it returns index 0.
0 is a falsy variable. 0 == false.
Look at https://secure.php.net/manual/en/types.comparisons.php what kind of values match to which result when doing loose comparisan(two ==) in the boolean column
You can better flip the if statements, to test for the false first.
We don't need an "else" here because either the code will abort in the if statement, or it will continue.
Saves an indentation level.
if($result === false) {
echo "FAIL";
exit;
}
// success
Three === means an exact match on value AND type
That's because in section A,
array_search($request_IP, $list_Array) will return zero.
so next condition line would compile as following:
if ($result) // if (0)
this condition will always return false.
To fix this issue. you have to use following line
if ($result === FALSE)
Because in your first example array_search will return 0 - because the first occurence of 8.8.8.8 is the first item. PHP is designed "weakly", so an assertion of "0" and boolean false will be true (false == 0) and an assertion of 1 and true will also be true (true == 1). This can be very tricky - as for example strpos returns 0 if a pattern is in the beginning of a string, in that case you would need to write your condition like (strpos($string, $search) !== false) - simply checking the return type "weakly" would result in a logic error (!strpos($string, $search).
You will have to adopt the condition.
I would recommend to use in_array
if (in_array($request_IP, $list_Array) === true)
will do
You should also have a look at this question:
What are the benefits (and drawbacks) of a weakly typed language?
Weak types is not bad design, its concept, if you use PHP or any other weakly typed language for business logic, you will need to be extra careful, using strict comparison only (=== instead of ==, !== instead of != and explicit comparison instead of negation) is a good start.

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.

Search php string - %like% sql

Right now I use stristr($q, $string) but if
$string = "one monkey can jump 66 times";
$q = "monkey 66";
I want to find out if this string contains both monkey and 66.
How can i do that?
you could use both stristr and strpos.
as it is reported in this post, the second method is faster and less memory intensive.
well, check this lines out:
// here there are your string and your keywords
$string = "one monkey can jump 66 times";
$q = "monkey 66";
// initializate an array from keywords in $q
$q = explode(" ", $q);
// for every keyword you entered
foreach($q as $value) {
// if strpos finds the value on the string and return true
if (strpos($string, $value))
// add the found value to a new array
$found[] = $value;
}
// if all the values are found and therefore added to the array,
// the new array should match the same object of the values array
if ($found === $q) {
// let's go through your path, super-man!
echo "ok, all q values are in string var, you can continue...";
}
if(stristr('monkey', $string) && stristr('66', $string)) {
//Do stuff
}
simply post your variable value by giving them a variable $monkey,$value ($monkey jumps $value) and then fetch its value
You can use the strpos() function which is used to find the occurrence of one string inside another one:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
Note that the use of !== false is deliberate (neither != false nor === true will work); strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are').

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)

Am i using strpos correctly?

I am trying to determine whether a word is present within a string of text, then if the word is present, print the relevant string. I'm having issues because this code appears to be working for some of my users but not all of them.
$active = $db->query("SELECT * FROM activity ORDER BY aTIME DESC LIMIT 15");
while($activity = $db->fetch_row($active))
{
$haveact = $activity['activity'];
$username = $r['username'];
if(strpos($haveact, $username))
{
print " <div class='activitydiv'>
{$activity['activity']} &nbsp&nbsp&nbsp&nbsp<small><font color='grey'>
{$activity['aTIME']}</font></small>
</div>";
}
}
Apart from what is suggested in the other answers, I would re-write the whole code to perform the string search in the query. For example like this:
<?php
$active = $db->query("SELECT * FROM (SELECT * FROM activity
ORDER BY aTIME DESC LIMIT 15)
WHERE activity LIKE \"%" . $db->escape($r['username']) . "%\";");
while($activity=$db->fetch_row($active))
{
print "<div class='activitydiv'>
{$activity['activity']} &nbsp&nbsp&nbsp&nbsp<small><font color='grey'>
{$activity['aTIME']}</font></small>
</div>";
}
?>
Please note that strpos returns the position of the found text. So for instance, when the word you are searching for is at the beginning of the the string the function will return '0'. Given that 0 is a false value, when you use the function like you did even though the word is found it will not be true. The correct usage of strpos is:
if (strpos($haystack, $needle) !== false) // Note the type check.
{
// your code...
}
Moreover, this function is case sensitive by default. You can use stripos for case insensitive search.
EDIT
From the manual:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE
Check the following examples to understand better:
strpos('the quick brown fox jumps over the lazy dog', 'the'); // Returns 0 (false value)
strpos('the quick brown fox jumps over the lazy dog', 'quick'); // Returns 4 (true value)
strpos('the quick brown fox jumps over the lazy dog', 'THE'); // Returns false (case sensitive)
Like Hauke P. mentioned - don not do this with PHP. You WANT to filter the matching rows with your database. If you do not want to use WHERE row LIKE %foo% because you need more power, you can even use REGEX in MYSQL. Just do not process the data with PHP. It is a design failure if you do so.
Check out the MySQL Help files about LIKE, SELECT, and REGEX.
hint: http://www.mysql.com/
strpos has the possibilty to return 0 and FALSE which are basically the same "value"
you need to check type and value like
strpos($haveact,$username) !== FALSE
strpos() returns a boolean FALSE if needle isn't found; and an integer value for its offset in the string if it is found. That offset can be 0, which equates to Boolean FALSE in a loose comparison.
Use
if(strpos($haveact, $username) !== FALSE)
as an alternative you can try php's preg_match function :
if (preg_match("/{$to_search}/" , $subject)) {
// your code to process
}
Another option, I usually use because it's shorter :)
if (strpos($haveact, $username) !== false) {
// In string.
}

Categories