The question is how to get value from preg_match() function the shortest way possible.
Let say, I know my string ends with digits. I'm sure! 100%!! Its in stone!!! What I need, is the value...
So far I do
preg_match('/(\d+)$/', $mystring, $m);
echo $m[1];
Is there a way to do this in one line of code?
I tried:
echo preg_match('/(\d+)$/', $mystring, $m)[1];
Error returned....
Any ideas?
Use preg_replace() instead:
echo preg_replace('/^.*?(\d+)$/', '$1', $str);
Explanation:
^ - assert position at the start of the string.*? - match any character (except newline characters)\d+ - match (and capture) one or more digits$ - assert position at the end of the string$1 - the contents captured by the first capturing groupNot that I'm advocating this, but in this particular case, you could do it this way:
echo $m[preg_match('/(\d+)$/', $mystring, $m)];
It's too convoluted and brittle to put in maintainable source, but I thought it was an interesting example of pointers and reference passing, so I wanted to put it up here. It relies on there being exactly one match (which is guaranteed by preg_match, but not preg_match_all), and the desired text being in the first group, but it works.
http://ideone.com/eWZoCD
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With