Link to home
Start Free TrialLog in
Avatar of UltraFlux
UltraFluxFlag for Canada

asked on

quick regex help (replace the last "-" with a "." so the file returns)

blah-blah-blah-blah-blah-flv

What can I use to replace the last "-" with a "." so the file returns

blah-blah-blah-blah-blah.flv

Thanks for the help. Would be great to know how to match the last char and replace with another.
Avatar of DrDamnit
DrDamnit
Flag of United States of America image

You don't need regular expressions. Do a regular find and replace:

Search -flv
Replace: .flv

If you really want regular expressions.
Well, depends on what you are looking to use, but you could use something like this in PHP:

SUBSTR("blah-blah-blah-blah-blah-flv",0,STRLEN("blah-blah-blah-blah-blah-flv"-4).".".SUBSTR("blah-blah-blah-blah-blah-flv",-3)

That would make sure to put the period in the right spot, and you don't need to know what "flv" is. It can be anything.

Same would apply to the last bar replacement. Take the total length of the string, subtract 1, and concatenation the right character.

Or, if you need more of a case type structure, then use SUBSTR("some string",-1) to get that last character, and then replace it using the above based on your case.
ASKER CERTIFIED SOLUTION
Avatar of larsrohr
larsrohr
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of UltraFlux

ASKER

I intend to exactly what I said in the question.

Find the last "-"
Replace with "."

Seems like larsrohr's solution will work, however I haven't finalized it yet.
This tests out OK.
<?php // RAY_temp_ultraflux.php
error_reporting(E_ALL);

// ORIGINAL
$old = 'blah-blah-blah-blah-blah-flv';

// DESIRED
$new = 'blah-blah-blah-blah-blah.flv';

// TRANSFORM AND TEST
$med = transform($old);
if ($med == $new) echo 'Success!';

// A FUNCTION TO HANDLE THE TRANSFORMATION
function transform($str, $dlm = '-', $rep = '.')
{
    $arr = explode($dlm, $str);
    $end = array_pop($arr);
    $new = implode($arr, $dlm) . $rep . $end;
    return $new;
}

Open in new window

While Ray's answer looks to work just fine, if regex is what you want, then regex is what you shall Have! ;-)

s/-(flv)($|\b)/.$1/ig

Open in new window

should work just fine in perl, and

preg_replace_all("/-(flv)($|\b)/i",".$1",$str);

Open in new window

should work just fine in PHP.

However, if it's not always going to be "flv" at the end, simply replace flv in the regexes above with

\w+?

Open in new window

works as expected, much appreciated