在比较PHP中的字符串之前,编码统一 [英] Make encoding uniform before comparing strings in PHP

查看:118
本文介绍了在比较PHP中的字符串之前,编码统一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一项功能,要求我获取网页的内容,然后检查该网页是否存在某些文字。这是一个反向链接检查工具。

I'm working on a feature which requires me to get the contents of a webpage, then check to see if certain text is present in that page. It's a backlink checking tool.

问题是这个功能在大多数时间运行,但偶尔,它标记一个页面,当没有链接的链接显然有。我已经跟踪到视觉上比较输出中的字符串的点,他们匹配很好,但使用==运算符,php告诉我,他们不匹配。

The problem is this - the function runs perfectly most of the time, but occasionally, it flags a page for not having a link when the link is clearly there. I've tracked it down to the point of visually comparing the strings in the output, and they match just fine, but using the == operator, php tells me they don't match.

认识到这可能是某种编码问题,我决定看看会发生什么,如果我在他们使用base64_encode(),所以我可以看到,如果这样做产生不同的结果之间的两个字符串完全相同)。

Recognizing that this is probably some sort of encoding issue, I decided to see what would happen if I used base64_encode() on them, so I could see if doing so produced different results between the two strings (which appear to be exactly the same).

我的怀疑被确认 - 使用base64_encode对比较的字符串产生了不同的字符串。发现问题!问题是,我不知道如何解决它。

My suspicions were confirmed - using base64_encode on the strings to be compared yielded a different string from each. Problem found! The problem is, I don't have any idea how to solve it.

有一些方法,我可以使这些字符串基于输出的文本(匹配) ,所以当我比较他们在php,他们匹配?

Is there some way I can make these strings uniform based on the outputted text (which matches), so that when I compare them in php, they match?

推荐答案

我不是完全卖你的信念,编码。 PHP将以相同的格式在其内部存储所有的字符串。你能试试这段代码吗?它会比较两个字符串中每个字符的ascii值,这可能会通过直观比较字符串来显示您看不到的内容。

I'm not entirely sold on your belief that it is the encoding. PHP is going to internally store all its strings in the same format. Could you try this code? It will compare the ascii value of each character in both strings, which might reveal something you're not seeing by visually comparing the strings.

$str1 = ...;
$str2 = ...;

if(strlen($str1) != strlen($str2)) {
  echo "Lengths are different!";
} else {
  for($i=0; $i < strlen($str1); $i++) {
    if(ord($str1[$i]) != ord($str2[$i]) {
      echo "Character $i is different! str1: " . ord($str1[$i]) . ", str2: " . ord($str2[$i]);
      break;
    }
  }
}

这篇关于在比较PHP中的字符串之前,编码统一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆