如果第1行匹配,则获取第2行的内容

时间:2012-12-20 12:59:02

标签: php regex variables preg-match

下面的代码选择包含单词“Homepage:”的每一行,并提取分号后面的内容。然而,我想要的是,如果匹配“主页:”这个词,下一行的内容应该被抓取并放入变量。

怎么可能这样做?

if (preg_match( '/Homepage:/', $text, $match )) {
    $pieces = explode(':', $text);
    $urls[] = trim($pieces[1]);
}

示例:

Homepage:    <--- if match
http://www.fooland.com    <--- grab this and put in variable

3 个答案:

答案 0 :(得分:2)

if (preg_match('/Homepage:.*\n(.*)/', $subject, $regs)) {
    $result = $regs[1];
}

<强>解释

Homepage: # Match Homepage:
.*        # Match any characters except linebreaks
\n        # Match a linebreak
(.*)      # Match and capture the contents of the entire line

答案 1 :(得分:1)

您可以尝试使用php

中的 explode()
$urlResult = explode(':', $url)
echo $urlResult[0];

答案 2 :(得分:0)

您可以尝试使用正则表达式'/Homepage:\n/'

相关问题