php preg_replace question
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.ideon开发者_开发百科e.com/Q80v3] its outputting:
'__f_o_o__B_a_r__1__'
And I can't work out why that is.. and 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)
<?php
echo preg_replace('/[^\w\d]+/', '_', trim(' foo Bar #1 -'));
?>
Output:
foo_Bar_1_
It seems to work if you use a +
instead of a *
EDIT
Actually, that outputs _foo_Bar_1_
instead of foo_Bar_1
. However, I don't know if there's a regex-only way to do that. Because you're giving it stuff at the beginning and end of the string that you're telling it to replace with underscores.
The quickest way to actually do what you want that comes to mind is regex and trim:
$str = preg_replace('/[^a-zA-z0-9]+/', '_', $str);
$str = trim($str, '_');
EDIT 2 (MAYBE I'LL ACTUALLY READ YOUR QUESTION AND UNDERSTAND WHAT YOU WANT) Nevermind, jnpcl's answer works perfectly. And it's just one regex!
精彩评论