PHP Using RegEx to get substring of a string

前端 未结 4 471
自闭症患者
自闭症患者 2020-12-08 18:30

I\'m looking for an way to parse a substring using PHP, and have come across preg_match however I can\'t seem to work out the rule that I need.

I am parsing a web p

相关标签:
4条回答
  • 2020-12-08 18:39
    $string = "producturl.php?id=736375493?=tm";
    $number = preg_replace("/[^0-9]/", '', $string);
    
    0 讨论(0)
  • 2020-12-08 18:39

    Unfortunately, you have a malformed url query string, so a regex technique is most appropriate. See what I mean.

    There is no need for capture groups. Just match id= then forget those characters with \K, then isolate the following one or more digital characters.

    Code (Demo)

    $str = 'producturl.php?id=736375493?=tm';
    echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';
    

    Output:

    736375493
    
    0 讨论(0)
  • 2020-12-08 18:59
    <?php
    $string = "producturl.php?id=736375493?=tm";
    preg_match('~id=(\d+)~', $string, $m );
    var_dump($m[1]); // $m[1] is your string
    ?>
    
    0 讨论(0)
  • 2020-12-08 19:00
    $matches = array();
    preg_match('/id=([0-9]+)\?/', $url, $matches);
    

    This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.

    php.net/preg-match

    0 讨论(0)
提交回复
热议问题