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']}     <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']}     <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.
}
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.
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').
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;
I have the following JS:
if(window.location.href.indexOf("search.php") != -1
|| window.location.href.indexOf("list.php") != -1
|| window.location.href.indexOf("view.php") != -1
|| window.location.href.indexOf("contact.php") != -1) {
But want to convert it to PHP. What is the equivalent of indexOf in PHP or the best way to do this in PHP.
I don't understand the strpos examples people are linking to below. Perhaps an example more in line with what I have done in JS?
The question asks for an equivalent. PHP's strpos() does not work on an array, whereas javascript's indexOf does (by treating a string as an array automatically). So here's a PHP equivalent
function indexOf($array, $word) {
foreach($array as $key => $value) if($value === $word) return $key;
return -1;
}
// Example: indexOf(['hi','bye'], 'bye') returns 1
Although your JavaScript code is using indexOf(), PHP actually has a better way of handling what you want to achieve.
You simply have to check the script name in your URL, then perform an action(s) based on it.
In my opinion, PHP switch statement is better than if statements in combination with PHP strpos() function.
Below is an illustration of how you can achieve that using a PHP switch statement:
switch(basename($_SERVER['SCRIPT_NAME'])) {
case 'search.php':
// Script to run for search.php
break;
case 'list.php':
// Script to run for list.php
break;
case 'view.php':
// Script to run for view.php
break;
case 'contact.php':
break;
default:
// Perform code on anything except the above cases.
break;
}
strpos() should do the trick, also it returns boolean false on failure.
JS version:
The indexOf() method returns the position of the first occurrence of a
specified value in a string. This method returns -1 if the value to
search for never occurs. Note: The indexOf() method is case sensitive.
PHP version:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
Find the numeric position of the first occurrence of needle in the
haystack string. Returns the position of where the needle exists relative to the
beginning 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.
In reply to your secondary question, strpos could be used as follows:
if (strpos($_SERVER['SCRIPT_NAME'], "search.php") !== false
|| strpos($_SERVER['SCRIPT_NAME'], "list.php") !== false
|| strpos($_SERVER['SCRIPT_NAME'], "view.php") !== false
|| strpos($_SERVER['SCRIPT_NAME'], "contact.php") !== false) {
...though indeed Rawkode's answer is more elegant.
strpos();
You should use mb_strpos() if you're not using ISO-8859-1 encoding (UTF-8 or others).