结果应该如下:
- :ii‘i
- Customer Service Helplines
-
- British Airways Helpline
-
- 09040 490 541
它没有挑出正文文本,这是我们能料到的,因为图片质量太差。虽然识别了号码但是也有一些“噪声”。
为了提取相关信息,有如下几件事我们可以做。
你可以让Tesseract 把它的结果限制在一定的字符集内,所以我们告诉它只返回数字型的内容代码如下:
- $tesseract->setWhitelist(range(0,9));
但这样有个问题。它常常把非数字字符解释成数字而非忽略它们。比如“Bob”可能被解释称数字“808”。
所以我们采用两步处理。
-
尝试提取可能是电话号码的数字串。
-
用一个库轮流评估每一个候选字符,一旦找到一个有效电话号码则停止。
第一步,我们可以用一个基本的正则表达式。可以用谷歌电话库来确定一个数字串是否是合法电话号码。
备注:我已在Sitepoint 写过关于谷歌电话库的内容。
让我们给谷歌电话库添加一个PHP 端口,修改composer.json,添加:
- "giggsey/libphonenumber-for-php": "~7.0"
别忘了升级:
- composer update
现在我们可以写一个函数,输入为一个字符串,尝试提取一个合法的电话号码
- /**
- * Parse a string, trying to find a valid telephone number. As soon as it finds a
- * valid number, it'll return it in E1624 format. If it can't find any, it'll
- * simply return NULL.
- *
- * @param string $text The string to parse
- * @param string $country_code The two digit country code to use as a "hint"
- * @return string | NULL
- */
- function findPhoneNumber($text, $country_code = 'GB') {
-
- // Get an instance of Google's libphonenumber
- $phoneUtil = libphonenumberPhoneNumberUtil::getInstance();
-
- // Use a simple regular expression to try and find candidate phone numbers
- preg_match_all('/(+d+)?s*((d+))?([s-]?d+)+/', $text, $matches);
-
- // Iterate through the matches
- foreach ($matches as $match) {
-
- foreach ($match as $value) {
-
- try {
-
- // Attempt to parse the number
- $number = $phoneUtil->parse(trim($value), $country_code);
-
- // Just because we parsed it successfully, doesn't make it vald - so check it
- if ($phoneUtil->isValidNumber($number)) {
-
- // We've found a telephone number. Format using E.164, and exit
- return $phoneUtil->format($number, libphonenumberPhoneNumberFormat::E164);
-
- }
-
- } catch (libphonenumberNumberParseException $e) {
-
- // Ignore silently; getting here simply means we found something that isn't a phone number
-
- }
-
- }
- }
-
- return null;
-
- }
希望注释能解释这个函数在干什么。注意如果这个库没能从字符串中解析出一个合法的电话号码它会抛出一个异常。这不是什么问题;我们直接忽略它并继续下一个候选字符。
如果我们找到一个电话号码,我们以E.164的形式返回它。这提供了一个国际化的号码,我们可以用来打电话或者发送SMS。
(编辑:PHP编程网 - 黄冈站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|