0

I have problem with matching pattern in URL and getting the right result.

The URL example:

#1: http://www.example.com/webapp/first-text-vs-some-text.html
#2: http://www.example.com/webapp/first-text-a1-vs-sec-b2-text.html
#3: http://www.example.com/webapp/first-text-a1-vs-sec-b2-text-vs-third-c3-text.html
#4: http://www.example.com/webapp/some-text-a1-vs-sec-text-b2-vs-third-text-vs-last-text-c1.html

Result without -vs- (HINT: -vs- can be shown once or repetitive from above URLs):

#1: first-text and some-text
#2: first-text-a1 and sec-b2-text
#3: first-text-a1, sec-b2-text and third-c3-text
#4: some-text-1a, sec-text-b2, third-text and last-text-c1

Is there a way of PHP loop to do that?

There is a situation that -vs- in URL structure can be found once or multiple times.

Should I get my results with few patterns or can it be possible done with one pattern match?

Should I first split the given URL and then check for characters & symbols left or right of the -vs-?

Had You have that kind of situation ever? Any ideas?

Thanks a lot for help and sharing ideas to get final result!

4
  • What is the "right result"? Commented Apr 7, 2016 at 17:19
  • 1
    You are able to retrieve strings and you want to separate substrings by “-vs-”, right? Use explode( '-vs-', $string );. Regex can't capture (as separated) repeating groups Commented Apr 7, 2016 at 17:21
  • 1
    Can't you just use str_replace? Commented Apr 7, 2016 at 17:31
  • Thanks for ideas. Will try with explode() and str_replace() to get it working. Commented Apr 7, 2016 at 17:58

1 Answer 1

1

You can use the following regex ([^\/.]+?)(?:-vs-|\.\w+$) with preg_match_all to return the different parts before and after -vs-.

Regex demo

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

2 Comments

Any way to match given URL with slash / on ending instad of .html? Example: example.com/directory/… . If I test regex for above URL, the 4th (third) match does not shown up.
@Fritex Add another condition in the non-capturing group like so: ([^\/.]+?)(?:-vs-|\.\w+$|\/$). Demo

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.