PHP - Strpos Returning False Is Not Buggy?
I find it a bit buggy that strpos returns false instead of -1.
The equivalent C implementation returns -1:
int strpos(char s[], char t[]) { int i, j, k; for (i = 0; s[i] != '\0'; i++) { for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++) ; if (k > 0 && t[k] == '\0') return i; } return -1; }The problem with returning false is that false can also evaluate to 0 which can also happen to be the first index of a match. Therefore, you have a hard to find bug. I know that you can use the identity operator to check for falseness: ===. But wouldn't it be a better design for the function to just return -1? Similar Tutorialsprivate function _authenticate() { // if there's already an auth error if ( $this->_checkForMessageType('auth') ) { $this->_addMessage('auth', 3); self::__destruct(); return false; } $stmt = $this->_dbh->prepare("SELECT shopID FROM api_users WHERE shopID = ? AND API_key = ? LIMIT 1"); var_dump($stmt->execute(array($this->_shopID, $this->_key))); echo $stmt->rowCount(); // authenticate key / shop id if ( !$stmt->rowCount() ) { $this->_addMessage('auth', 3); self::__destruct(); return false; } $this->_addMessage('auth', 4); } I am using PDO with MySQL driver and ATTR_EMULATE_PREPARES => true, however, when I run this code I get the output: Code: [Select] bool(false) 0{"auth":{"3":""}} Any ideas why PDOStatement::execute is returning false? I get no connection errors, no PDOExceptions, the db structure is correct, and there is valid data in the database. Any help appreciated, thanks. I am trying to take all the information from $results and input it into a text file, sometimes we get duplicates in $results so I want to check the text file for the entry before writing it in so we don't get duplicates in the text file. However inarray keeps returning false, even when I echo out the two arrays and they match? Code: [Select] $myfile = "complete.txt"; foreach ($results['info'] as $data) { $output=$fields['firstname']."|".$record['lastname']."|".$record['address']."|".$record['number']."\n"; $handle = fopen($myfile, "r"); $contents = fread($handle, filesize($myfile)); fclose($handle); $list = array(); $list = explode("\n",$contents); $list = array_map("trim", $list); $current = $output; echo in_array($current,$list) ? $current.' exists' : $current.' does not exist'; if (in_array($current,$list)) { print "duplicate"; } else { if($file=fopen($myfile, "a")) { //open file for writing fwrite($file, $output); //write to file } } } Does anyone see anything wrong with the SQL? This function keeps returning false. Thank you for your time. Code: [Select] function insert_survey1($survey1_anwers) { // extract order_details out as variables extract($survey1_anwers); $username = $_SESSION['valid_user']; $conn = db_connect(); // select user_id based on the entered data $query = "SELECT user_id FROM user WHERE gender = '".$gender."', birth_range = '".$birth_range."', degree_year = '".$degree_year."' username = '".$username."'"; $result = $conn->query($query); //if the resulting user_id exists (AND has the POST data just entered, since the query must match those to return a row) , if($result->num_rows>0) { //return the current row of the result set as an object and place it into user variable $user = $result->fetch_object(); //set variable for user_id to the fetched user object data representing the user_id int he db( because it was fetched from the sql select result) $user_id = $user->user_id; //update the fields since the user exists already. $query = "UPDATE user SET gender = '".$gender."', birth_range = '".$birth_range."', degree_year = '".$degree_year."' WHERE user_id = '".$user_id."'"; // $query = "UPDATE `alumni_survey`.`user` // SET `gender` = '".$gender."', // `birth_range` = '".$birth_range."', // `degree_year` = '".$degree_year."' // WHERE `user`.`user_id` = '".$user_id"'"; } else { //otherwise, if the user doesn't exist already insert this new data. $query = "INSERT INTO user (gender, birth_range, degree_year) VALUES('".$gender."','".$birth_range."','".$degree_year."') WHERE user_id = '".$user_id."'"; $result = $conn->query($query); if (!$result) { return false; } } return $user_id; } Hi, I'll be honest don't have a clue what I am doing but a friend asked me to look into her site, she gets the following error at the top of this page http://www.morairaluxuryvillas.com/rentals/villalist.php Warning: strpos() [function.strpos]: Offset not contained in string in /home/morairal/public_html/rentals/villalist.php on line 85 the code on the line 85 is: $secondfstemp = strpos($block1, ".", $firstfs); I am more than willing to look into but don't know where to start - anyone have any ideas? Thanks for your time:-) Hi Guys I've been trying to work on my OS Commerce site, but for some reason I'm getting this error on the main index.php page. Welcome Guest! Would you like to log yourself in? Or would you prefer to create an account? Feel free to click any of the links below to access the main categories. Warning: strpos() [function.strpos]: Empty delimiter. in /var/www/vhosts/XXXXXX.co.uk/httpdocs/shop/index.php on line 319 319 shows this: if (isset($cPath) && strpos('_', $cPath)) { Any ideas where this error comes from? Hi I am new to php, I am trying to capture the url and place into a variable but I only get the 1st digit to show, I just cant see what I am doing wrong. Sorry to ask such a basic question but I just can't work it out, I have attached a screen shot of all me code, your help would be very very much appreciated. hi there, is there a difference between if($var == false) and if(false == $var) thankyou! Hello
I am working on a 3 field variable that is given in an array with A-Z and 1-26 and 26 words in total, being randomized and insert in database via mysql but it must checks to be sure there is no duplicate of any values at all.
here is my code, I managed to make the first value to work but the 2nd and 3rd doesnt.
<? // connection data mysql_connect("localhost", "user", "pass") or die("error ".mysql_error()); mysql_select_db("dbname") or die("error ".mysql_error()); function GenerateNumber(){ // selects random number $randomNumber = rand(1,26); return $randomNumber; } function GenerateLetter(){ // selects random position number in letters array to select an alphabet $LetterPosition = rand(0,25); $alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'); $randomLetter = $alphabet[$LetterPosition]; return $randomLetter; } function GenerateWord(){ // selects random word from an array -same method as letter $wordPosition = rand(0,25); $words = array('ah','book','cup','dice','elephant','flute','gum','house','idol','jumpingjacks','kite','lunchbox','matress','novel','olive','pumpkin','queen','rooster','stove','teacup','unicorn','violin','walurus','xerox','zebra'); $randomWord = $words[$wordPosition]; return $randomWord; } for($x=0; $x<=25;){ //generate letter,number,and word $randomLetter = GenerateLetter(); $randomNumber = GenerateNumber(); $randomWord = GenerateWord(); echo '<b>Generated Variables:</b>[ '. $randomLetter.' ][ '.$randomNumber.' ][ '.$randomWord.' ]<br />'; // there is data in the table, check if there is letter already assigned $first = mysql_query("SELECT * FROM test WHERE a_char='$randomLetter'"); if(mysql_num_rows($first) == 0){ //no letter is found, check if there is number already assigned $second = mysql_query("SELECT * FROM test WHERE aint='$randonNumber'"); if(mysql_num_rows($second) == 0){ //no number is found, check if there is word already assigned $thrid = mysql_query("SELECT * FROM test WHERE aword='$randomWord'"); if(mysql_num_rows($third) == 0){ //there is no letter,number, and word found in db, great! go ahead and insert! $fq = "INSERT INTO test (a_char,aint,aword) VALUES ('$randomLetter','$randomNumber','$randomWord')"; $final = mysql_query($fq); //increment the loop $x++; echo('[ '. $randomLetter.' ][ '.$randomNumber.' ][ '.$randomWord.' ] has been added in row '.$x.'<br /><br />'); }else{ echo("Repeated Word: ".$randomWord." generating another: "); //there is word already assigned, select another! $randomWord = GenerateWord(); echo($randomWord.'<br /><br />'); } }else{ echo("Repeated Number: ".$randomNumber." generating another: "); //there is number already assigned, select another! $randomNumber = GenerateNumber(); echo($randomNumber.'<br /><br />'); } }else{ echo("Repeated Letter: ".$randomLetter." generating another: "); //there is letter already assigned, select another! $randomLetter = GenerateLetter(); echo($randomLetter.'<br /><br />'); } } mysql_close(); ?> How do I do two strpos conditions? here is kinda what I have.... if (strpos($val,'Sparring') && ($val,'Ecas') { } Hi Im having a problem finding the posistion of a div tag I tried this piece of code $fpos= strpos($snip, "<div id=\"footer\">") Then this piece $fpos= strpos($snip, "<div id="footer">") The $snip is the entire html document I thought maybe the \ might be causeing problem but without it Then i tried this any suggestions guys Thanks James Hello, Am a little puzzled on how to effectively determine if a character exists in a string. I am trying to come to grips with the function strpos but its a little confusing. If am searching for an underscore in a string and want to echo yes if the string contains an underscore, would the code below be right? Would it be right to exclude booleans TRUE and FALSE Example 1 Code: [Select] <?php $string = "Hello_World"; if(strpos($string, "_")) { echo "yes"; } OR do I have to include the booleans TRUE/FALSE Example 2 Code: [Select] <?php $string = "Hello_World"; if(strpos($string, "_") == TRUE) { echo "yes"; } Hey guys I need some help I did a quick search and couldn't find my problem so I hope I didn't miss it. Anyways, I've got a bit of code in which when a specific website is visited, it generates a log. This is to track the number of times the website gets visited and from where. I know this sounds like a counter, but it's different. I'm having a problem though, because right now, I can't get it to generate for ONLY the website entered. It generates for EVERY website instead of just the specific one. Right now this is what I have.. if (strpos($_url, "MY_SPECIFIC_WEBSITE") //URL { I've tried adding to it to fix it, but I'm obviously still learning PHP and am sick of strugglnig. If anyone could please help I would appreciate it so much. Which is most efficient for finding a string within a string? Eregi or strpos? Currently im using Eregi to check a string again an array of blocked words and retrun true if one is present. But it seems i can do it also with strpos... so which is best function to use ? I have a string like this: Code: [Select] $data = "<a href="">Arbitrary characters. Bla bla bla</a><p>123456789</p><p>$10,100</p><p>01/02/2010</p><p>01/02/2011</p>"; What I am trying to accomplish is to extract the number between the first <p> tags as well as the date between the last <p> tags. I can extract the first number just fine by doing this: Code: [Select] $opening_p = strpos($data, '<p>'); $opening_p += 3; $closing_p = strpos($data, '</p>'); $length = $closing_p - $opening_p; // The length of the number changes, so I need to know the current length $first_number = substr($data, $opening_p, $length); However, no matter what I do, the position for the fourth <p> comes out to be the same as the first <p> In other words, this produces exactly the same number for the <p> Code: [Select] $opening_fourth_p = strpos($data, '<p>', 4); $opening_fourth_p += 3; So even with the offset in strpos, the position is exactly the same for both "extractions". So to conclude, both of these returns the same value: Code: [Select] $opening_p = strpos($data, '<p>'); $opening_fourth_p = strpos($data, '<p>', 4); Is there something I miss? This will be an easy one for you guys...
One of the fields in a MySQL database is a varchar() that was populated using a checkbox method and can contain more than one response. in this case i have blue, yellow, green and want to check if the field contains blue before echoing the statement to the screen. How would i use strpos in this case? ive tried a few thigns and get syntax error. The below of course works if the field ONLY contains blue. if (($row['colorsyoulike']) =='blue') { echo "<tr>"; echo "<td>Blue is an available Color!</td>"; } thanks. Great alliteration in the title. *Ahem* Anyway I have this code that I use for my chat system, And I'm making a command system. However when I send the command, It picks it up as a command etc. but it is so stubborn it will not realise it. I'm guessing it's my human error again like usual but take a look, See if you can help me (Please note the filea() function is for debugging it's telling me where the code (by printing to file) is taking me as the way I'm using it I can't just use echo or print whatever and see the results on a page) if(substr($text, 0, 2)=="::"){ //the command trigger is :: filea("Picked up the start of the command"); $subt1=substr($text, 2); //seperate the command trigger, In my case :: to execute the command. filea("Just checking the string... ".$subt1); $comms=array('ban', 'mute', 'cls', 'sysm', 'unmute'); $match=false; foreach($comms as $comm){ $commtest2=strpos($subt1, $comm); if($comtest2!=false){ //I also tried ==true first with no success $match=true; $command=$comm; break; } } filea("Ran command checker"); if($match==false){ filea("Command not found match=".$match); exit; //Exit out if there were no matching commands. } When I run this command: ::mute test this is the log that gets given to me, As you can see from the code this is what I put in there. Code: [Select] 3:07 AM) Logged in //this isn't in the code... (3:07 AM) Set text (3:07 AM) finding stats of person gergy008 (3:07 AM) Not muted. Continue... (3:07 AM) Has powers //up to here. But you don't need this. :) (3:07 AM) Picked up the start of the command (3:07 AM) Just checking the string... mute test (3:07 AM) Ran command checker (3:07 AM) Command not found match= As you can see I'm like -.- it's finding that the command is mute but it won't find mute in that string. It's dumb. Can someone help me find what the heck is wrong with this? I will be truely greatful Thanks! Hi I have a page pulling information from mysql table, it lists names, I have these inside a hyperlink so that where there is a website listed for that record then the user can click on the name and move to their website. Only thing is that what happens if there is not a website for that record. I wanted a script so that if there is a website address listed then it prints the hyperlink but where there is not a website address listed that only the name is printed and it is not a hyperlink. I understand that the strpos can be used for this I have written a script but it is only printing out the name even when there is a website address in the row. What is wrong? PHP Version 5.3.4 Any help very much appreciated Code: [Select] <?php $website = $org_website; $link = 'http'; $weblink = strpos ($website,$link); if ($weblink === !false) { echo "<a href=\"$org_website;\"> FindOrganiserName($org_id); \"> FindOrganiserName($org_website); </a>"; } else { echo FindOrganiserName($org_id); } ?> Code: [Select] $mystring = "|Signature"; $findme = '|'; $pos = strpos($mystring, $findme); echo $pos; echo's 0 supposed to echo out 1....? why not work thanks How can I enable it to check for Code: [Select] | using strpos? Hy ya'll! I've been trying to programatically read a string, but with no success. Code: [Select] function get_between($input, $start, $end) { $substr = substr($input, strlen($start)+strpos($input, $start), (strlen($input) - strpos($input, $end))*(-1)); return $substr; } $string = 'open -greetings hello -bye seeya'; echo get_between($string, '-greetings ', ' -bye'); // Output: hello echo get_between($string, '-greetings ', ' -'); // Outputs nothing echo get_between($string, '-greetings ', ' '); // Outputs nothing } It turns out that I don't know if "-bye" will always follow the value of "-greetings", so I can't call everything in between like the first way even tough it works fine in this example. Given that those values will always be a single word, I can use a whitespace as a delimiter to the right, but for some reason it won't return anything whatsoever, not even an error code. Any ideas how to get it done? Txs a bunch! Hi all I am grabbing the _SERVER['REQUEST_URI'] and trying to compare it but this doesnt work $currpage = $_SERVER['REQUEST_URI'];//when i echo this i get ' / ' $home = '/'; //but this doesnt work if(strpos($currpage, $home)){echo 'test works';} PS It will work if i use if($currpage == $home){echo 'test2';} Any ideas? Thanks, Magnetica |