开发者

Regular Expression to find the job id in a string

开发者 https://www.devze.com 2023-01-01 23:24 出处:网络
Please could someone help me, i will b开发者_如何学编程e forever appreciative. I\'m trying to create a regular expression which will extract 797 from \"Your job 797 (\"job_name\") has been submitted\

Please could someone help me, i will b开发者_如何学编程e forever appreciative.

I'm trying to create a regular expression which will extract 797 from "Your job 797 ("job_name") has been submitted"

or "Your Job 9212 ("another_job_name") has been submitted" etc.

Any ideas? Thanks guys!


Are there any special conditions about grabbing the number?

To grab the first number, just use /\d+/ with preg_match.

if (preg_match('/\d+/', $subject, $match)) {
    $job_id = (int) $match[0];
}

Otherwise you could do something like the following which searches for a number preceeded by "job" (case-insensitive).

if (preg_match('/job (\d+)/i', $subject, $match)) {
    $job_id = (int) $match[1];
}

(There are better alternatves for this regex, but best to keep things simple at first.)


Another option would be to move away from regular expressions into more basic parsing of a string:

sscanf($subject, 'Your Job %d ("%[^"]")', $job_id, $job_title);
// use $job_id and $job_title however you like

Of course, similar could be done with preg_match but it's good to offer alternatives.


If the rest of the string is guaranteed to be same, a simple \d+ would suffice.

Otherwise, use Your job (\d+) and read the first captured group.

preg_match("/Your job (\d+)/", $str, $matches);
echo $matches[1]; //prints the id.

Edit: modified to get job name

preg_match("/Your job (\d+) \("(.+?)"\)/", $str, $matches);
echo $matches[1]; //prints the id.
echo $matches[2]; //prints the job name.
0

精彩评论

暂无评论...
验证码 换一张
取 消