<a href=\".\/(viewtopic.php\?f=15&amp;t=[0-9]+)\" class=\"topictitle\">([#\w\s_\-!$%&()?.,'\":;{}\/\\|’=\[\]+\–\™ ]+)<\/a>

i have this regex ina ction when i use it in software like regex buddy its ok but when i use it in php it just dont work it .throw no error at all..but it produce zero result.
it is made to match this

<a href="./viewtopic.php?f=15&amp;t=119871" class="topictitle">Twilight Graphic Novel</a>

the match is ok but when i write
this

<?php
$contents = file_get_contents($url);

preg_match_all("/<a href=\".\/(viewtopic.php\?f=15&amp;t=[0-9]+)\" class=\"topictitle\">([#\w\s_\-!$%&()?.,'\":;{}\/\\|’=\[\]+\–\™ ]+)<\/a>/i",$contents,$out);


$len=count($out[0]);
echo $len;
?>

$len outputs is zero although when i used this in regexbuddy with the sample page source it worked like a charm..
any ideas?

Dani AI

Generated

Your pattern and ’s manual test show the regex itself can work; ’s suggestion to try a non‑greedy match was a good direction. The practical difference is almost always the fetched input: the string you think is in $contents is what differs in real runs. Start by proving the page you fetched actually contains the target anchors.

Try these quick diagnostics first:

var_dump($contents !== false, strlen($contents));
echo substr($contents, 0, 1000);

if (strpos($contents, 'class="topictitle"') !== false) {
    echo "anchor class present\n";
} else {
    echo "anchor not present\n";
}

If those checks show the expected markup is not present, the fetch is the problem. Check allow_url_fopen, redirects, HTTP status and server blocks (403, 301, etc.). A simple cURL fetch will show headers and the real body:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
var_dump($info['http_code']);
echo substr($response, 0, 500);

If the content is present but your regex still gives zero matches, common causes are multiline text and encoding. Add PCRE modifiers so . can match newlines (s) and so pattern/subject are treated as UTF-8 (u), or decode entities first with html_entity_decode(). For robust HTML extraction avoid fragile regex and use DOM parsing:

libxml_use_internal_errors(true);
$dom = new DOMDocument;
$dom->loadHTML($contents);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//a[contains(concat(" ",normalize-space(@class)," ")," topictitle ")]');
foreach ($nodes as $a) {
    $href = $a->getAttribute('href');
    $title = trim($a->textContent);
    echo "$href -> $title\n";
}

Summary: reproduce the exact fetched text (inspect $contents), verify HTTP/encoding, then either adjust PCRE (add s/u, decode entities) or switch to DOMDocument for a reliable scraper.

Recommended Answers

All 4 Replies

What is the output when you run:

print_r($out)

Knowing that output can sometimes give a great insight into where these sorts of problems lie (or at least it has been useful when I've been doing regex work :))

as expected print_r($out) throws empty array

Do you get anything different if you do:

preg_match_all("/<a href=\".\/(viewtopic.php\?f=15&amp;t=[0-9]+)\" class=\"topictitle\">(.+?)<\/a>/i",$contents,$out);

Just wondering whether a non-greedy ".+" match might be better. If that doesn't it, it probably means it's something in the first regex match section.

Are you sure $contents contains the string you say it does? When I manually assign the string you want to match to $contents the match works and there is something in the $out array.

<?php
$contents = <<<END
<a href="./viewtopic.php?f=15&amp;t=119871" class="topictitle">Twilight Graphic Novel</a>
END;
preg_match_all("/<a href=\".\/(viewtopic.php\?f=15&amp;t=[0-9]+)\" class=\"topictitle\">([#\w\s_\-!$%&()?.,'\":;{}\/\\|’=\[\]+\–\™ ]+)<\/a>/i",$contents,$out);

$len=count($out[0]);
echo '$len is equal to ' . "$len\n";
print_r($out);

//Gives the following output:
//$len is equal to 1
//Array
//(
//    [0] => Array
//        (
//            [0] => <a href="./viewtopic.php?f=15&amp;t=119871" class="topictitle">Twilight Graphic Novel</a>
//        )
//
//    [1] => Array
//        (
//            [0] => viewtopic.php?f=15&amp;t=119871
//        )
//
//    [2] => Array
//        (
//            [0] => Twilight Graphic Novel
//        )
//
//)
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.