【问题标题】:PHP preg_match_all: extract specific linesPHP preg_match_all:提取特定行
【发布时间】:2014-11-26 16:21:00
【问题描述】:

我有问题。我需要得到这样的页面的一些行:

Text text text ...

Porto-Portugal-May-2013
Barcelona-Spain-April-2013

Text text text text text ...

Madrid-Spain-April-2013

Text text text ...

我需要过滤器,以便只显示以下内容:

Porto-Portugal-May-2013
Barcelona-Spain-April-2013
Madrid-Spain-April-2013

(带有 3 个破折号的行)

preg_match_all 或者其他函数可以吗?

我使用 cURL 来获取页面内容。

我试过了:

$body = " Text text text ...

Porto-Portugal-May-2013
Barcelona-Spain-April-2013

Text text text text text ...

Madrid-Spain-April-2013

Text text text ...";

preg_match_all("/^(.*?)-(.*?)-(.*?)-(.*?)\/",$body, $match);

for($i=0;$i<sizeof($match[1]);$i++)
  {
    echo $match[1][$j].'<br/>';
  }

谢谢。

【问题讨论】:

  • 请分享您的尝试。 SO 不是编码服务。
  • 我已经用示例更新了问题。谢谢。
  • 你得到的结果有什么问题?
  • 它不返回结果。它是空的......

标签: php regex curl preg-match preg-match-all


【解决方案1】:

^ 表示“字符串的开头”。

添加 m 修饰符使其表示“行首”。

那就更简单了:

preg_match_all("/^(?:[^-\n]+-){3}[^-\n]+$/m",$body,$matches);

var_dump($matches[0]);

这应该输出一个数组,其中包含匹配的每一行。

【讨论】:

  • 我得到这个结果:array (size=3) 0 => string ' Text text text ... Porto-Portugal-May-2013 ' (length=47) 1 => string 'Barcelona-西班牙-2013 年 4 月 Text text text text text ...' (length=61) 2 => string 'Madrid-Spain-April-2013 Text text text ...' (length=45)
  • @ptCoder 啊,当然,它允许行在中间匹配。我已经编辑了答案,看看是否有帮助?
  • 是的。这是完美的。非常感谢。
  • 再问一个问题:如果你用#字符替换破折号,你在preg_match_all代码中修改了什么?
  • 对,好吧,那么你需要[^-#\n]+[-#],而不是[^-\n]+-
【解决方案2】:

在你的最后一行定义年份的情况下,你不需要正则表达式来完成这个任务,如下:

<?php
$yearsList = array(2013, 2014);
$body = " Text text text ...


Porto-Portugal-May-2013
Barcelona-Spain-April-2013

Text text text text text ...

Madrid-Spain-April-2013

Text text text ...";

$arr = explode("\n",$body);
$res = array();
foreach ($arr as $items){
  $itemArr = explode('-', $items);
    foreach ($itemArr as $item){
      if (in_array($item, $yearsList)) $res[] = $items;
    }
}
echo "<pre>";
print_r($res);
?>

查看此演示:http://codepad.org/fdhwEJC4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 2012-04-28
    • 1970-01-01
    相关资源
    最近更新 更多