Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex: how to get value in one line of code?

Tags:

regex

php

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?

like image 776
cyadvert Avatar asked Dec 02 '25 09:12

cyadvert


2 Answers

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 group
like image 67
Amal Murali Avatar answered Dec 04 '25 21:12

Amal Murali


Not 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

like image 23
FrankieTheKneeMan Avatar answered Dec 04 '25 21:12

FrankieTheKneeMan