I've already got a bit of working code but I need someone to help explain why it works if they can!
I am using PHP to replace anything in a string if it is not either a-z, A-Z, 0-9, a comma, a semicolon, an underscore or a hyphen (which ultimately should represent either a single username, or a comma/semicolon separated list of usernames).
The following works:
$data = preg_replace('/[^,;a-zA-Z0-9_-]/s', '', $data);
But the following does not:
$data = preg_replace('/[^a-zA-Z0-9_-,;]/s', '', $data);
Why will this only work when the comma and semicolon are at the start? Putting them at the end seems to break things (this is what I tried initially when I came across /[^a-zA-Z0-9_-]/s.
As an aside, I am also using the following to trim any trailing semicolons (plural) or commas (plural) and someone may be able to suggest a more efficient and/or elegant way to do this?:
if(preg_match('/;$/', $data))
{
$data = rtrim($data, ';' );
}
if(preg_match('/,$/', $data))
{
$data = rtrim($data, ',' );
}
Thanks for any help :)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…