Question:
PHP - how do I check if a string starts with a letter and replace so that it does?
Black-Light
2011-04-20 14:47:35 UTC
so in PHP I want to make it so that a certain is checked for what character it starts with
and if it does not start with a letter a-zA-Z then replace it so that it starts with a letter

so I want some characters like 0-9, - and _ to be allowed but not before the first letter of the string

so that
$username = '-_-User-Name8';
will become
$username = 'User-Name8'

(I have already solved the problem with all characters like $=?!|,.:;ยต and so on. with a simple
$username = preg_replace('/[^a-z0-9A-Z_-]/','',$username);
now I only need to make it start with a letter)
Three answers:
Dasaru
2011-04-27 11:12:53 UTC
I'm not an expert on regular expressions, but it seems fine.



I don't think you need to use $first_character though. You could write something like this:



while( ! ctype_alpha( substr($username, 0, 1) ) ){

$username = substr($username, 1);

}



Instead of checking for the value of $first_character which is [[ substr($username, 0, 1) ]] - you should just plug it's value in the condition. It'll update each time it loops.



A sidenote: If you're using this for validation for users, I would personally throw an error if the user tried to add characters at the beginning of their username and make them retype their username. It's probably not in your best interest to change the user's username without their knowledge.
stockett
2016-12-18 10:43:46 UTC
Php Starts With
joto
2016-09-30 10:25:06 UTC
Php String Starts With


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...