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
https://forums.phpfreaks.com/topic/249564-string-starts-with/
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
https://forums.phpfreaks.com/topic/249564-string-starts-with/#findComment-1281251
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
https://forums.phpfreaks.com/topic/249564-string-starts-with/#findComment-1281258
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.