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
Your regular expression:
preg_match('/^\[\#([0-9]+)\].+/i', $string, $array);
That's a way you could do it:
<?php
$subject = "[#1234] Subject";
$pattern = '/^\[\#([0-9]+)/';
preg_match($pattern, $subject, $matches);
echo $matches[1]; // 1234
?>
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'];
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.
You can try this:
preg_match('~(?<=\[#)\d+(?=])~', $txt, $match);
(?<=..)
is a lookbehind (only a check)
(?=..)
is a lookahead