All non alphanumeric but also allow _
Moderator: General Moderators
- shiznatix
- DevNet Master
- Posts: 2745
- Joined: Tue Dec 28, 2004 5:57 pm
- Location: Tallinn, Estonia
- Contact:
All non alphanumeric but also allow _
Just as the title states, I need to strip out everything that is not alphanumeric but I need to allow the _ character through. How do I do this?
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
Code: Select all
$data = preg_replace('#[^a-z_]+#i', '', $data);- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
\W (Uppercase) ?
Code: Select all
preg_replace('/\W+/', '', $string);- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
oops, I forgot to add numbers. 
Code: Select all
$data = preg_replace('#[^a-z0-9_]+#', '', $data);- R4000
- Forum Contributor
- Posts: 168
- Joined: Wed Mar 08, 2006 12:50 pm
- Location: Cambridge, United Kingdom
To allow space use: (I THINK! don't bite me if i'm wrong)
Just basicly add anything you want inbetween the [ and ]
If you wanted to allow the ; char. :
Code: Select all
$data = preg_replace('#[^a-z0-9 _]+#', '', $data);If you wanted to allow the ; char. :
Code: Select all
$data = preg_replace('#[^a-z0-9;_]+#', '', $data);- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
my brain must be off today, I forgot the i modifier for the pattern in the updated one. 
with space
Code: Select all
$data = preg_replace('#[^a-z0-9 _]+#i', '', $data);- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Or even easier:feyd wrote:my brain must be off today, I forgot the i modifier for the pattern in the updated one.
with spaceCode: Select all
$data = preg_replace('#[^a-z0-9 _]+#i', '', $data);
#[^\w ]+#
No "i" needed
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
You're mistaken..d11wtq wrote:Or even easier:feyd wrote:my brain must be off today, I forgot the i modifier for the pattern in the updated one.
with spaceCode: Select all
$data = preg_replace('#[^a-z0-9 _]+#i', '', $data);
#[^\w ]+#
No "i" neededI never get why people use a-z0-9_ when that's precisely what \w is
Code: Select all
<?php
$str = '';
for($i = 0; $i < 256; $i++)
{
$str .= chr($i);
}
echo preg_replace('#[^\w]#', '', $str);
?>Code: Select all
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyzâèîÄÜ£₧ƒ¬▓│╡╣║└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷°∙·√ⁿ²■