开发者

strcasecmp() not working properly in my php script

In the snippet of code below, I'm using the strcasecmp() function. The function works fine for the first name match but does not for the last name.

For example if I have the name Joe Black in for names file and submit blanks for the name, the value of $xxx and开发者_如何学编程 $yyy are -3 and -6 respectively. If submit the name I get $xxx = 0 and $yyy = -1.

Can someone tell what I am missing or doing wrong??

Thanks

Chris

<?php 
$fname = $_POST["fname"]; 
$lname = $_POST["lname"];

print "First Name: " .$fname; 
print "< br/>"; 
print "Last Name: " . $lname;

$namesFile = "namesFile.txt";

$numLines = count(file($namesFile)); 
print "< br/>"; 
print "Lines: " . $numLines;

$fh = fopen ($psswrdFile, "r");

for ($i=1; $i <= $numLines; $i++) 
{ 
$lineData = fgets($fh); 
print "< br/>"; 
print $lineData;

list($firstName, $lastName) = explode(" ", $lineData);

print "First Name: " .$firstName;  

print "Last Name: " . $lastName;  

$xxx = strcasecmp($fname,$firstName);  

print "name " . $xxx;  

$yyy = strcasecmp($lname, $lastName);  

print "password" . $yyy;  
}

?>


Your problem is that fgets() includes the end-of-line character in the line it reads. This means that your $linedata for "Joe Black" is actually "Joe Black\n", i.e. it includes a newline. Therefore your $lastName ends up as "Black\n" rather than "Black".

As a quick fix, I would use stream_get_line() instead of fgets, specifying "\n" as the delimiter. This will work very similarly to fgets(), except it doesn't read the delimiter into the string you get back.

Or keep your fgets() and just strip the newline out of the string it gives you... As @kavisiegel mentions, trim() is an easy way of doing that (although technically I guess rtrim() will be faster!)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜