Skip to main content
Known Participant
May 23, 2012
Question

finding number in a string

  • May 23, 2012
  • 2 replies
  • 3131 views

I am trying to find a number in a string from my database to replace it.  Here is my funciton:

function findUserID($friendsString, $userToFind){

          echo $friendsString . " " . $userToFind;

          $pos = strpos($friendsString,$userToFind);

          if($pos){

                    return true;

          }

          return false;

}

it returns "25,29 25".  How can it not find 25 in that string?

This topic has been closed for replies.

2 replies

Participating Frequently
May 24, 2012

Because string positions start at 0, not 1. Read the warning and solutions here: http://www.php.net/manual/en/function.strpos.php

Known Participant
May 24, 2012

I understand that it starts at 0.  it should still work.  i had it working before.  i must've changed something. 

here is my code for passing to the function:

$query = mysql_query("SELECT friends, pendingFriendRequest

FROM members

WHERE username = '$userID'");

if (mysql_affected_rows() > 0) {

          $row = mysql_fetch_array($query) or die(mysql_error());

          $friends = $row['friends'];

          $pendingFriends = $row['pendingFriendRequest'];

}

// If the user exists in the waiting list, then

//continue (we must confirm that they are first by checking the DB

$test = findUserID($pendingFriends, "25");

if($test){

          // If they are, then continue to add them

          $test = confirmFriend($pendingFriends, "25");

          if($test) {

                    echo "<br />You have confirmed " . findUserName(24) . "as a friend.";

          } else {

                    echo "<br />Error: Please try again, or contact us.";

          }

} else {

          echo "<br />Error: You either have this person as a friend already, or there was an internal error.";

}

Participating Frequently
May 24, 2012

>I understand that it starts at 0.  it should still work.

No, it will not work.

>$test = findUserID($pendingFriends, "25");

If the position of the found string is 0, then $test equals 0

>if($test){

0 evaluates to boolean false, so this test fails, making it appear that the string was not found. Try

if($test === false)

Rob Hecker2
Legend
May 24, 2012

Is there are reason you are not doing this with just an UPDATE query? Something like the following:

UPDATE 'table' SET 'column' = REPLACE('column', '25' 'replacementdata')

Known Participant
May 24, 2012

thanks for this, but first i have to check if the user exists first in the field.

Rob Hecker2
Legend
May 24, 2012

So it's not just replacing everywhere it encounters 25? At any rate, even if I don't quite understand what you are trying to do,  it still seems like the best way to do this is all in MySQL, not PHP.