【问题标题】:Extract informations with php preg_match_all使用 php preg_match_all 提取信息
【发布时间】:2014-09-25 11:36:27
【问题描述】:

我正在尝试修改脚本以提取信息:

有页面例如:

<ul class="tags">
<li><div class="tag"><a href="http://www.url1.com" title="url1">title 1</a></div></li>
<li><div class="tag"><a href="http://www.url2.com" title="url2">title 2</a></div></li>
</ul>

我想要标题 1,标题 2

我有这个代码:

$m=array();
preg_match_all("/<a href="(.*)" title="(.*)">(.*)<\/a>/i", $buff,$m);
$info['tags']=trim(strip_tags($m[3]));
$cats=array_map('trim',$cats);
$info['tags']=implode(',',$cats);

但是我得到了 trim 和 array_map 的错误。

感谢您的帮助。

【问题讨论】:

  • 我建议为此使用 HTML 解析器,尤其是 DOMDocument

标签: php arrays preg-match-all trim


【解决方案1】:

代码中的第一个错误在第 3 行:

$info['tags']=trim(strip_tags($m[3]));

这里对于函数strip_tags 应该给出字符串作为参数,但$m[3] 是数组。一个快速的解决方法是:

$info['tags']=array_map('strip_tags',array_map('trim',$m[3]));

$info[tags] 现在是:

[tags] => Array
   (
       [0] => title 1
       [1] => title 2
   )

比应用内爆函数:

$info['tags'] = implode(',', $info['tags']);

干杯,碧儿

【讨论】:

  • 我希望 $info[tags] 成为标题 1,标题 2
  • 在这种情况下,您可以使用 implode 函数:$info[tags] = implode(",", $info[tags]),结果将是 title 1, title2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-09
  • 1970-01-01
  • 2022-01-03
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
相关资源
最近更新 更多