user2647541
user2647541

Reputation: 77

php Regular expressions basic

I want to regex thread_id in this html code by using php

<a id="change_view" class="f_right" href="pm.php?view=chat&thread_id=462075438105382912">

I wrote this code however it return empty array to me

  $success = preg_match_all('/pm\.php\?view=chat&thread_id=([^"]+)/', $con, $match2);

is there any problem in my php code ?

Upvotes: 0

Views: 54

Answers (3)

Jobst
Jobst

Reputation: 559

if (preg_match('/thread_id=[0-9]*/', $line, $matches))
    $thread_id = $matches[0];

Upvotes: 0

afzalex
afzalex

Reputation: 8652

Well, you said it is giving you an empty array. But it is not. Here is the value returned by print_r()

Array
(
    [0] => Array
        (
            [0] => pm.php?view=chat&thread_id=462075438105382912
        )
    [1] => Array
        (
            [0] => 462075438105382912
        )
)

But It is not returning what you want it to. The regular expression to get string that comes after thread_id= and before & or " is :

/(?<=thread_id=).*(?=\"|&)/

Working example :

<?php 
$con = '<a id="change_view" class="f_right" href="pm.php?view=chat&thread_id=462075438105382912">link</a>';
$match2 = Array();
preg_match_all('/(?<=thread_id=).*(?=\"|&)/', $val, $arr);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

Output :

Array
(
    [0] => Array
        (
            [0] => 462075438105382912
        )
)

Upvotes: 1

Burning Crystals
Burning Crystals

Reputation: 1167

If you're only looking for the thread_id, this should do it.

$success = preg_match_all('/(thread_id=)([\d]+)/', $con, $match2);

Upvotes: 0

Related Questions