'PHP's preg_match() to return a value in the string after a substring
I have an issue whereby I need to return a number value that exists after a fixed sub string regardless of the other characters in the string around it. I am sort of there, because the following works.
$string = "Created Ticket_Id#234 (Some info)";
preg_match("/Ticket Id_#([0-9]+\s)/", $string, $res);
print $res[1];
Outputs: 234
But then when I get the string as follows.
$string = "Created Ticket_Id#234";
preg_match("/Ticket Id_#([0-9]+\s)/", $string, $res);
print $res[1];
Outputs: nothing
Is there a better way of doing this without looking for the white space?
Solution 1:[1]
Yes, just use \b, the word boundary special character class, instead of \s.
So your pattern would be:
/\bTicket_Id#([0-9]+)\b/
Note that I pulled the special character class out of the capturing parenthesis as you need not capture it.
Also I noticed that your string had Ticket_Id#234, while your regex had Ticket Id#234. You should change the underscore in your regex based on what the case really is.
Solution 2:[2]
Just remove the final \s
Depending on whether the string or the regular expression is correct
/Ticket_Id#([0-9]+)/
or
/Ticket Id_#([0-9]+)/
This will stop at the last digit found and return the searched number.
Solution 3:[3]
A few. You could use a word boundary:
"/Ticket Id_#([0-9]+)\b/"
Check against the end of the string:
"/Ticket Id_#([0-9]+)(\s|$)/"
Or just collect all the digits:
"/Ticket Id_#([0-9]+)/"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
| Solution 2 | Peter Mortensen |
| Solution 3 | FrankieTheKneeMan |
