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.
精彩评论