Search code examples
phpregexpreg-replacealphanumericsnakecasing

Replace one or more non-alphanumeric characters with underscores


I was expecting this:

echo preg_replace('/[^a-zA-z0-9]*/', '_', ' foo Bar #1 -');

to output this:

'foo_Bar_1_'

But using ideone [http://www.ideone.com/Q80v3], it's outputting:

'__f_o_o__B_a_r__1__'

And I can't work out why that is nor how to achieve what I want, that it outputs 'foo_Bar_1_'.

If I remove the *

echo preg_replace('/[^a-zA-z0-9]/', '_', ' foo Bar #1 -');

it outputs:

'_foo_Bar__1__'

but I don't want lazy match (only one underscore pr. replacement).


Solution

  • <?php
        echo preg_replace('/[^\w\d]+/', '_', trim(' foo Bar #1 -'));
    ?>
    

    Output:

    foo_Bar_1_