1

I am writing a script that needs to download images related to a product ID array to an external website. Here are the possible product ID combinations.

  • ABC1234AB
  • ABC1234AB-CD
  • ABC1234AB-CDE
  • ABC1234ABC

I need to be able to convert them to their URL equivalent on the manufacturer's website, which are (In the same order):

  • abc1234_ab
  • abc1234_ab_cd
  • abc1234_ab_cde
  • abc1234_abc

I am looking for a Regex to use with preg_replace that would do the trick. Thanks in advance!

2 Answers 2

1
$output = strtolower(preg_replace('~\d\K(?=[A-Z])|-~', '_', $input));

\K removes that is matched on the left from the match result, so , the digit before the letter is not a part of the match and will not be replaced.

(?=...) is a lookahead assertion that checks if a letter if following, it isn't a part of the match result too and will not be replaced too.

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

Comments

0

I'm a noob in regular expressions but I`ll give it a shot.

Input: /([A-Z]+)\d+([A-Z]+)\-([A-Z]+)/

A-Z matches uppercase alpha characters \d matches numbers

"+" is used to repeat

And in the replacement callback use strtolower on the matches and join them how you want :P

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.