Joshua F Posted October 21, 2011 Share Posted October 21, 2011 I'm working on a register script which has an array of strings that a username can not start with, but the script I'm using checks to see if the items in the array are anywhere in the username. Here's my code. $blockedWordsInUsername = array('mod', 'm0d', 'admin', 'adm1n', '4dm1n'); foreach($blockedWordsInUsername as $username) { if(strstr($_POST['username'], $username) == true && !$error) { $error = '<p style="text-align: center;">Sorry, that username is no longer available.</p>'; } } What I'm trying to do is make it so your name can't start with the items in the array. Link to comment https://forums.phpfreaks.com/topic/249564-string-starts-with/ Share on other sites More sharing options...
requinix Posted October 21, 2011 Share Posted October 21, 2011 So don't use strstr(). strncmp is one option, or you could use substr and a direct comparison. Link to comment https://forums.phpfreaks.com/topic/249564-string-starts-with/#findComment-1281244 Share on other sites More sharing options...
Joshua F Posted October 21, 2011 Author Share Posted October 21, 2011 So don't use strstr(). strncmp is one option, or you could use substr and a direct comparison. So would it be something like this?(I doubt it) foreach($blockedWordsInUsername as $username) { for ($i = 0; $i < 9; $i++) { if(substr($_POST['username'], $i) == in_array($_POST['username'], $blockedWordsInUsername) && !$error) { $error = '<p style="text-align: center;">Sorry, that username is no longer available.</p>'; } } } Link to comment https://forums.phpfreaks.com/topic/249564-string-starts-with/#findComment-1281251 Share on other sites More sharing options...
requinix Posted October 21, 2011 Share Posted October 21, 2011 So would it be something like this?(I doubt it) I doubt it too. Link to comment https://forums.phpfreaks.com/topic/249564-string-starts-with/#findComment-1281254 Share on other sites More sharing options...
Joshua F Posted October 21, 2011 Author Share Posted October 21, 2011 <?php class Server { function startsWith($haystack, $needle) { $length = strlen($needle); return (substr($haystack, 0, $length) === $needle); } function endsWith($haystack, $needle) { $length = strlen($needle); $start = $length * -1; //negative return (substr($haystack, $start) === $needle); } } ?> foreach ($blockedWordsInUsername as $username) { if ($server->startsWith($_POST['username'], $username)) { $error = '<p style="text-align: center;">Sorry, that username is no longer available.</p>'; } } Got it. Link to comment https://forums.phpfreaks.com/topic/249564-string-starts-with/#findComment-1281258 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.