How to use preg_match to extract data?

女生的网名这么多〃 提交于 2019-12-12 07:22:26

问题


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?


回答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.




回答2:


You can try this:

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

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

(?=..) is a lookahead




回答3:


Your regular expression:

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



回答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
?>



回答5:


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'];


来源:https://stackoverflow.com/questions/18035478/how-to-use-preg-match-to-extract-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!