2014-10-04 156 views
0

我有两个字符串,一个字符串是API的输出,另一个字符串以longtext的形式存储在MYSQL数据库中。我试图用 来比较这两个字符串,所以我做了以下操作:PHP中的奇怪字符串

echo $stringfromMyDatabase; 
echo "<br">; 
echo $stringfromMyApi; 
echo "<br>"; 
echo strcmp($stringfromMyDatabase,$stringfromMyapi); 
echo "<br>"; 
echo "StringfrommyDatabase :".strlen($stringfromMyDatabase)."and StringfromApi:".strlen($stringfromMyApi); 

,这里是我得到的输出:

1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 8 9 
1 
StringfrommyDatabase :25 and StringfromApi:17 

尽管字符串看起来完全相似,而附和他们,如何 我知道如何以及在何处这两个字符串不同,如何打印 包含所有特殊字符的两个字符串?

任何帮助与正确的解释将不胜感激!

+0

愚蠢的错字错误; s strcmp()@Pang – 2014-10-04 10:08:38

回答

0

使用var_dump($ stringfromMyDatabase,$ stringfromMyApi)并看看这个。

+0

:显示字符串(25)“1 2 3 4 5 6 7 8 9” – 2014-10-04 10:15:59

+0

都是字符串? – 2014-10-05 17:05:07

0

字符串根据您对它们执行的strlen而不同。我很确定你的数据库存储了字符串和额外的空格字符(空格,标签,...)。

试试这个:

$len = strlen($stringfromMyDatabase); 
for ($i = 0; $i < $len; $i++) { 
if ($stringfromMyDatabase[$i] != $stringfromMyapi[$i]) 
    echo "--{$stringfromMyDatabase[$i]}-- (code " . ord($stringfromMyDatabase[$i]) . 
    ") != --{$stringfromMyapi[$i]}-- (code " . ord($stringfromMyapi[$i]) . ") @ char pos {$i}\n"; 
} 

这将告诉你在哪里字符串不同,哪些是不同的(可能非打印)字符。

+0

为什么它应该是?我将从api中检索到的相同字符串存储到数据库中。使用插入查询命令但是检索字符串的长度不同,为什么会发生这种情况? – 2014-10-04 10:26:55

+0

我认为,如果不使用这些冗长的代码行,我们可以使用str_replace(“\”,“\\”,$ string),但在这种情况下,“\\”报告错误为什么会这样? – 2014-10-04 10:27:44

+0

你必须逃避你的反斜杠。关于我给你的那段代码,它唯一的目的是向你展示两个字符串之间的区别。试试看看有什么不同。 – NaeiKinDus 2014-10-04 10:29:26