0

I know that this works:

preg_match('/\d+/', '1234 Subject', $matches);
echo $matches[0]; // 1234

But I'm curious if there's a built-in function that just returns the first match, a la:

echo mysteryFunction('/\d+/', '1234 Subject'); // 1234

Without having to store the results in an array and having to then reference an array element separately?

If not, why not, is there a good reason?

Thanks

Codemonkey
  • 4,455
  • 5
  • 44
  • 76

1 Answers1

2

No there isn't. But for fun (I don't propose using this), if you use a capture group ():

echo preg_split('/(\d+)/', '1234 Subject', null, PREG_SPLIT_DELIM_CAPTURE)[1];

Just like your echo $matches[0]; you will get a Notice: Undefined offset if there is no match.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • What if [there is no match](https://3v4l.org/HXCo2)? I don't think this is a good answer. I'd use it as a comment. – Wiktor Stribiżew Jun 20 '19 at 17:48
  • @WiktorStribiżew: It's not supposed to be a good answer, just fun. Same as OP's `echo $matches[0];` if there is no match https://3v4l.org/sSK4V – AbraCadaver Jun 20 '19 at 17:52