preg_replace trouble
am trying to leave only a-zA-Z0-9._ in a text using :
$new_pgname=preg_replace('|(^[a-zA-Z0-9_\.])|s','',$new_pgname);
but guess what开发者_JAVA百科 ... right , it's not working ! any help plz ?
Thanks .
try this:
$new_pgname=preg_replace('%[^a-z0-9._]%i', '', $new_pgname);
This will maintain upper and lowercase characters
What you should do - replace one or many characters that are NOT a-z A-Z 0-9 _ or .
. So you need to use the following expression: [^a-zA-Z0-9_\.]+
What this means:
[]
- define a character class
^
- NOT these characters
+
- one or more
Code:
$new_pgname = "(*_&HF&)*FH)FE*H)_#(*#F(*&HEF&HF*&By7bv07f87asFB087aFgbh08aj9smf,f.,efw3.g3454-w54w.34.tw\43t4/.g34/g34g/3g434h8j)*7bh*&)Fg803723r6y";
echo $new_pgname . '<br />';
$new_pgname = preg_replace ('/[^a-zA-Z0-9_\.]+/', '', $new_pgname);
echo $new_pgname . '<br />';
OUTPUT:
(*_&HF&)*FH)FE*H)_#(*#F(*&HEF&HF*&By7bv07f87asFB087aFgbh08aj9smf,f.,efw3.g3454-w54w.34.tw#t4/.g34/g34g/3g434h8j)*7bh*&)Fg803723r6y<br />
_HFFHFEH_FHEFHFBy7bv07f87asFB087aFgbh08aj9smff.efw3.g3454w54w.34.twt4.g34g34g3g434h8j7bhFg803723r6y<br />
You dont need to escape the dot (.) inside an alternation
You need to put the carat /in/side the bracket
What you have will only attempt to match characters at the beginning of the string...the caret (^
) goes inside the character group to negate it.
$new_pgname=preg_replace('|([^a-zA-Z0-9_\.])|s','',$new_pgname);
It looks like you are trying to use a negated character range. In order to do that, you need to put the caret (^) inside the square braces, as the first character of the set, i.e.:
[^a-zA-Z0-9_.]
精彩评论