How to use preg_match to extract data?

12,757

Solution 1

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.

Solution 2

You can try this:

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

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

(?=..) is a lookahead

Solution 3

Your regular expression:

preg_match('/^\[\#([0-9]+)\].+/i', $string, $array);

Solution 4

That's a way you could do it:

<?php
$subject = "[#1234] Subject";
$pattern = '/^\[\#([0-9]+)/';
preg_match($pattern, $subject, $matches);

echo $matches[1]; // 1234
?>
Share:
12,757
Mic
Author by

Mic

Updated on August 12, 2022

Comments

  • Mic
    Mic over 1 year

    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 per my needs. If its silly question, please forgive me.

    I need to get the ID from a string with preg_match. the string is in the format

    [#1234] Subject
    

    How can I extract only "1234" from the string?

  • Mic
    Mic over 10 years
    It is not working if there is any prefix for the ID like Re : [#1234] Subject
  • nickb
    nickb over 10 years
    @Mic - That wasn't in your original post, but it's easily fixed by removing the ^ from the regex. I'll update my answer.
  • Mic
    Mic over 10 years
    I am sorry, if my question created a confusion.
  • nickb
    nickb over 10 years
    @Mic - Not a problem, I've updated my answer, please try again!