2

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?

2
  • 2
    The myFunction()[index] syntax is available in PHP 5.4: php.net/manual/en/migration54.new-features.php Commented Mar 6, 2014 at 15:25
  • @WesleyMurch +1 but that still wont work for the askers example since preg_match returns an int. Commented Mar 6, 2014 at 15:29

2 Answers 2

10

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
Sign up to request clarification or add additional context in comments.

1 Comment

Erroneous comment removed. Nice job +1
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.