【问题标题】:preg_match works in builder, but not in scriptpreg_match 在构建器中有效,但在脚本中无效
【发布时间】:2020-12-24 20:43:00
【问题描述】:

我正在创建一个正则表达式 https://www.phpliveregex.com/#tab-preg-match

代码如下:

$input_line = 'Sector(s) : Basic Materials Industry : Gold Full-time employees :  ';
preg_match('/Industry : (.*) Full-time employees :/', $input_line, $output_array);

在在线工具中,结果符合预期,即“Gold”。

但是在我的代码中这并没有发生:

echo preg_match('/Industry : (.*) Full-time employees :/', $arr[5], $industry_arr);

返回 0。

数组 $arr 如下所示:

Array ( [0] => [1] => [2] => [3] => [4] => [5] => Sector(s) : Basic Materials Industry : Gold Full-time employees : [6] => [7] => )

在开发人员工具中,我的数组看起来像这样,我很困惑:

(
    [0] => 
    [1] => 
    [2] => 
    [3] => 
    [4] => 
    [5] => Sector(s) : Basic Materials 
Industry : Gold 
Full-time employees :\  
    [6] => 
    [7] => 
)

如果我执行 echo $arr[5] 我会得到以下信息:

Sector(s) : Basic Materials Industry : Gold Full-time employees :

我想知道非中断空间是否在这里引起了问题?

提前致谢

【问题讨论】:

  • 试试echo $arr[5],然后在你的问题中包含这个。

标签: php regex preg-match screen-scraping


【解决方案1】:

问题在于 &nbsp 字符。

很遗憾,此处发布的解决方案不起作用 https://www.php.net/manual/en/function.trim.php

有效的是:

  $string = htmlentities($arr[5], null, 'utf-8');
  $clean_string = str_replace(" ", "", $string);
  $clean_string = html_entity_decode($clean_string);

我在这里找到了它: replace   characters that are hidden in text

这将字符串清理为“正常”字符串,并且运行正则表达式按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    相关资源
    最近更新 更多