Remote Dashes withen they appear betwen a letter and number or nuumber and letter

I am trying to remove dashes from a string. Simple enough, using preg_replace()

but in this case, I want to remove dashes ONLY when they appear between a letter OR between a number and a letter.

I am not too comfy with regex, expecially when I can’t use Postix expressions.

Say given a string like “123-ab” or “ab-123” I want to remove the dashes such that the strings returned are “123ab” and “ab123” respectively.

I think I can do this with the preg_replace function. Your direction is appreciated.


<?php
echo preg_replace(
    '~(?<=[a-z\\d])-(?=[a-z\\d])~i',
    null,
    '-5445-fsd-4234-vxcv-'
);
#-5445fsd4234vxcv-
?>

:wink:

Whoa! Anthony!

bows Much Respect for your regex skills!

Your script works beautifully, except for the case when the hyphen is between letters or between numbers. IN that case, I don’t want to remove the hyphen.

Can I brake it down into two difference calls to preg_replace?

Ok, breaking it up into two steps, I got the results I was looking for.

Take

$string1 = "--this is-123-4-aaa--"

$string1 = preg_replace(
    '~(?<=[a-z])-(?=[\\d])~i',
    null,
    $string1);

//produces 
//--this is123-4-aaa--

then I take that
and do

preg_replace(
    '~(?<=[\\d])-(?=[a-z])~i',
    null,
    $string1
)

//which produces 
//--this is123-4aaa--

Thank you very much for the guidance and example! :slight_smile:

Your two patterns could be combined into a single pattern; here’s one example, of course there are numerous other ways to achieve the same result but this one should hopefully be fairly clear (as far as this type of regex goes) about what it does.


echo preg_replace(
    '/-(?<=\\d-(?=[a-z])|[a-z]-(?=\\d))/i',
    '',
    '-123-abc-456-789-def-ghi-'
);
// -123abc456-789def-ghi-