繁体   English   中英

多行正则表达式不起作用

[英]Multiline regular expression not working

我正在尝试从字符串$cool获取/story.php?title=googlegoogle-google-google 获得它的唯一方法是使用多行正则表达式。 我尝试了下面的代码,但是没有用。 谁能帮我这个?

<?php 

    $cool ='<li><span class="sidebar-vote-number"><a href="/story.php?title=gamestarts now">1</a></span><span class="sidebar-article"><a href="/story.php?title=googlegoogle-google-google" class="switchurl">GoogleGoogle Google Google</a></span></li>

        Published News</a></div>
        </div>
        <div class="boxcontent">
            <ul class="sidebar-stories">

        <li><span class="sidebar-vote-number"><a href="/story.php?title=googlegoogle-google-google">1</a></span><span class="sidebar-article"><a href="/story.php?title=googlegoogle-google-google" class="switchurl">GoogleGoogle Google Google</a></span></li>';


    preg_match('/Published News<\/a><\/div>
        <\/div>
        <div class="boxcontent">
            <ul class="sidebar-stories">

        <li><span class="sidebar-vote-number"><a href="(.*?)"/msU', $cool, $match);


    echo $match[1];


        ?>  

出什么问题了

preg_match('~Published News.*<li><span class="sidebar-vote-number"><a href="([^"]*)~ms', $cool, $match);

确保使用正确的变量$cool

您确定知道什么? 哪个模式?

“获得它的唯一方法是使用多行正则表达式。” 哦,不,不是。

除此之外,您还将数据辅助到一个名为$ cool的变量,但是将一个名为$ game的变量传递给preg_match()函数。

 preg_match('/Published News<\/a><\/div>
        <\/div>
        <div class="boxcontent">
            <ul class="sidebar-stories">

        <li><span class="sidebar-vote-number"><a href="(.*)">/msU', $cool, $match);

有用。

如果您的HTML字符串是半格式,则可以使用Xpath。 http://codepad.org/vVBFNY7r

<?php
$cool ='<ul><li>
<span class="sidebar-vote-number"><a href="/story.php?title=gamestarts now">1</a></span>
<span class="sidebar-article"><a href="/story.php?title=googlegoogle-google-google" class="switchurl">GoogleGoogle Google Google</a></span>
</li></ul>';
$dom = new DOMDocument();
$dom->loadHTML($cool);

$xpath = new DOMXPath($dom);
$elements= $xpath->query('//a/@href');

if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>[". $element->nodeName. "]";

    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}

输出:

<br/>[href]/story.php?title=gamestarts now
<br/>[href]/story.php?title=googlegoogle-google-google

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM