Jump to content

String Starts With...?


Joshua F

Recommended Posts

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
Share on other sites

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
Share on other sites

<?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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.