Getting correct values out of string

If you think about chats in online games or in general I think there is not many if any that allow spaces in usernames. If you wouldn’t allow spaces in the username it would make things a lot easier.

2 Likes

Then its extra work and is not one line anymore! But maybe pop-op form also be a good soluttion!

But i would really like it in form as i have right now if its possible. If not i will work other way

Assuming there wouldn’t be spaces in the username you could just do

$str = "/ban username 1 You didn't follow the rules.";
$parts      = explode(' ', $str);
$command    = $parts[0];
$username   = $parts[1];
$hours      = $parts[2];
$reason     = implode(array_slice($parts, 3, count($parts)), ' ');
1 Like

This is almost how i had it till now! Only i never had username with space till now and $reason seems to be better in your example as till now we used just one word to describe bad reason :smiley:

For better readability: explode() has a third parameter where you just can get the rest after a certain amount of splits. Also you can use the list() struct to directly transfer the information into the named variables.

2 Likes

Or, if it’s OK to require the mods to start the command with a leading delimiter, in this case /, why can’t you make them start other key words with a leading delimiter?

/ban user name here $5 reason

Easy (or easier) then to split out the command, the length of ban, anything between those two is the user name, anything after the length is the reason.

2 Likes

This is also not that bad idea! Thanks :slight_smile:

True… heres even shorter version based on @chorn’s comments.

$str = "/ban username 1 You didn't follow the rules.";
list($command, $username, $hours, $reason) = explode(' ', $str, 4);
3 Likes

Assuming a username can not contain a number on its own (e.g, “ScallioXTX 2”) you can also use

preg_match('~/ban (.+?) (\d+) (.+)~', $line);

See https://repl.it/repls/FunnyPromotedInternet for a live example

This works because the first part (.+?) is lazy and will stop matching as it finds a number on it’s own.

1 Like

In this case i will allow numbers! But thanks :slight_smile:

You miss the point here. @rpkamp said

The key is on its own i.e. without a space.

1 Like

Oh i now got it thanks to @Gandalf but there is 2 things wrong

  1. i also need full command in list like $action = $results[0]; // is: /ban or any other command
  2. as you said: ScallioXTX 2 will not work

:frowning:

But if i block spaces in username it works!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.