Remove spaces from $contactname php
I am trying to remove the spaces from $contactname. Right now if I view the code below I get:
First Last
If I replace $_SESSION['name'] with 'first last' I get:
firstlast
Any ideas on why this is only working when it is a static field?
$contactname=$_SESSION['name'];开发者_如何学Python
$contactname = preg_replace('/( *)/', '', $contactname);
echo $contactname."\n";
Updated Code with same problem:
$contactname=$_SESSION['name'];
$contactname = str_replace(' ', '', $contactname);
echo $contactname."\n";
Don't use preg_replace to remove spaces. Use:
str_replace(' ', '', $contactname);
It's faster.
Your regex should use the character class for whitespace, \s
:
$contactname = preg_replace('/\s+/', '', $contactname);
In order to replace anything like a space that might be in $_SESSION, or use str_replace
if it is guaranteed to only be spaces (because it doesn't need the regex engine and goes faster):
$contactname = str_replace(' ', '', $contactname);
精彩评论