0

JS:

'abc/foln'.match(/[^\/]*?\/?$/); // ['foln']

PHP:

preg_match_all('/[^\/]*?\/?$/', 'abc/foln', $e); // ['foln', '']
preg_match_all('/\/[^\/]*?\/?$/', 'abc/foln', $e); // ['/foln']
preg_match_all('/\/?[^\/]*?\/?$/', 'abc/foln', $e); // ['/foln', '']

How can i achieve the same result in PHP as in JS?

And would be interesting to know why this difference.

8
  • For shiggles, try preg_match_all('/[^\\/]*?\\/?$/', 'abc/foln', $e); in case the backslash needs to be escaped to a literal Commented Dec 28, 2018 at 23:58
  • 1
    result remains the same Commented Dec 29, 2018 at 0:00
  • 2
    Change [^\/]* to [^\/]+ so it doesn't match an empty string at the end. Commented Dec 29, 2018 at 0:01
  • great, works with the +, you can write an answer and maybe say why such difference Commented Dec 29, 2018 at 0:03
  • They are different because PHP and JavaScript are different languages that have nothing to do with each other. Commented Dec 29, 2018 at 0:05

1 Answer 1

2

You should use preg_match rather than preg_match_all. preg_match_all is analogous to using JavaScript .match() with a regexp with the g modifier, e.g.

console.log('abc/foln'.match(/[^\/]*?\/?$/g));

The reason you get an empty match when you return all matches is because the * and ? quantifiers will match empty strings, so the whole regexp matches the empty string at the end of the string.

There's generally little point to returning multiple matches when the regexp is anchored with ^ or $, since they can only match once (unless you're using the m modifier, which makes them match beginning/end of lines rather than the whole string).

Sign up to request clarification or add additional context in comments.

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.