Search code examples
phpregexreplacedelimited

Replace last delimiter with one character and if there is an earlier delimiter replace it with another character


I have two awesome input strings:

  1. my_awesome_string
  2. my_awesomestring

I'm trying to create a function that can convert the first underscore to a / if there is a second underscore in the string, but convert it to a - if there is no second underscore.

Expected output:

  1. my/awesome-string
  2. my-awesomestring

Can you help me convert my awesome string?


Solution

  • Another way:

    $first = strpos($str, '_');          // find first _
    $last = strrpos($str, '_');          // find last _
    $str = str_replace('_', '-', $str);  // replace all _ with -
    if($first !== $last) {               // more than one _ ?
        $str[$first] = '/';              // replace first with /
    }