How to use preg_match to extract data?

前端 未结 5 1927
无人及你
无人及你 2021-01-07 04:21

I am pretty new to the use of preg_match. Searched a lot for an answer before posting this question. Found a lot of posts to get data based on youtube ID etc. But nothing as

相关标签:
5条回答
  • 2021-01-07 04:47

    Your regular expression:

    preg_match('/^\[\#([0-9]+)\].+/i', $string, $array);
    
    0 讨论(0)
  • 2021-01-07 04:47

    That's a way you could do it:

    <?php
    $subject = "[#1234] Subject";
    $pattern = '/^\[\#([0-9]+)/';
    preg_match($pattern, $subject, $matches);
    
    echo $matches[1]; // 1234
    ?>
    
    0 讨论(0)
  • 2021-01-07 04:53

    To get only the integer you can use subpatterns http://php.net/manual/en/regexp.reference.subpatterns.php

     $string="[#1234] Subject";
     $pattern="/\[#(?P<my_id>\d+)](.*?)/s";
     preg_match($pattern,$string,$match);
     echo $match['my_id'];
    
    0 讨论(0)
  • 2021-01-07 04:59

    One solution is:

    \[#(\d+)\]
    

    This matches the left square bracket and pound sign [#, then captures one or more digits, then the closing right square bracket ].

    You would use it like:

    preg_match( '/\[#(\d+)\]/', '[#1234] Subject', $matches);
    echo $matches[1]; // 1234
    

    You can see it working in this demo.

    0 讨论(0)
  • You can try this:

    preg_match('~(?<=\[#)\d+(?=])~', $txt, $match);
    

    (?<=..) is a lookbehind (only a check)

    (?=..) is a lookahead

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