简体   繁体   中英

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 ?

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
        )
)
if (preg_match('/thread_id=[0-9]*/', $line, $matches))
    $thread_id = $matches[0];

如果您只在寻找thread_id,则应该这样做。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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