Reputation: 57
I've been trying to figure this out as I've never needed to do this before, but how would I remove 2 parts of the string? This is what I have so far..
str_replace('/pm ', '', $usrmsg)
$usrmsg would be what the user sent in my chat room, I've already removed /pm but this needs 2 variables...
1: The username 2: The message to the user
Usernames don't have spaces, therefore after the 2nd word, the message to the user will be inputted. How can I remove the first 2 parts of the string separately?
Upvotes: 1
Views: 116
Reputation: 36989
$string = '/pm username bla bla bla';
list($comand, $user, $text) = explode(" ", $string, 3);
// $comand --> /pm
// $user --> username
// $text --> bla bla bla
or simply
list(, $user, $text) = explode(" ", $string, 3);
Upvotes: 1
Reputation: 3143
You could use the explode() method as follows
$tokens = explode(' ', "/pm matt hi matt this is maatt too", 3);
print_r($tokens);
The first element of array will have "/pm", the second username and the third will have the message.
Upvotes: 0
Reputation: 1836
If you're familiar with regular expressions, use something like this:
$inp = '/pm matt Hey Matt, here\'s my message to you...';
preg_match('~^\/pm\s?(?P<username>.*?)\s(?P<message>.*?)$~', $inp, $matches);
echo $matches['username'] . PHP_EOL;
echo $matches['message'];
Upvotes: 0
Reputation: 1985
Use regular expressions. Should be something like this:
if(preg_match('#^/pm ([A-Za-z]+) (.*)$#',$message,$matches))
var_dump($matches);
Upvotes: 1
Reputation: 28793
So you've removed the /pm
, and you just need the next word?
// remove the /pm
$usrmsg = str_split('/pm', '', $usrmsg);
// split the usrmsg by space
$parts = str_split(' ', $usrmsg);
// the username is the first part
$username = $parts[0];
Upvotes: 0