0

I have a string:

https://domain.tld/123456/api/v1/projects/45242457-foo-bar.json

And I'm trying to match '45242457-foo-bar' using:

preg_match('~"/projects/(.*).json"~', $url, $matches, PREG_OFFSET_CAPTURE);

This keeps returning zero matches. Why?

5
  • Why do you have double quotes around the URL? Commented Mar 19, 2013 at 17:05
  • 1
    What are the surrounding " for? Commented Mar 19, 2013 at 17:05
  • 1
    Consider using parse_url() (php.net/manual/en/function.parse-url.php) to get info about urls. It is a much easier and better solution than a regex. Commented Mar 19, 2013 at 17:05
  • Great questions. I saw another SO post where it said preg_match required delimiters around the pattern. I'll try to find it ... Commented Mar 19, 2013 at 17:09
  • @doremi You have delimiters around your pattern. The tildes (~) are your delimiters in this case Commented Mar 19, 2013 at 17:09

1 Answer 1

2

You need to escape your period (and a greedy *):

~"/projects/(.*?)\.json"~
Sign up to request clarification or add additional context in comments.

4 Comments

He does, but that's not the cause of the problem, the cause is a greedy *
Overlooked that. Regex modified accordingly.
@DaveRandom Actually not a problem here. Works just fine leaving the asterisk as-is. The problem is actually the double quotes. Just fixing that makes this work. Although I agree the . should be escaped to stick with what the OP is trying to do
Would be more helpful to put the entire solution (this works) preg_match('~/projects/(.*?)\.json~', $project->url, $matches, PREG_OFFSET_CAPTURE);

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.