'Pattern for splitting a string
I'm looking to split this string:
/server hostname:port username:password
into:
Array ( [0] => hostname
[1] => port
[2] => username:password )
I don't wish for /server to be stored.
Hostname, port, username and password will all vary in lengths.
I'm not sure if I should be using preg_split for this, and what the matching pattern should be?
Thanks
Solution 1:[1]
Exploding the string and splitting it's parts can get you what you need. Note that the example below does nothing to check the string is actually in that format. It would be wise to check that.
$str = '/server hostname:port username:password';
$bits = explode(" ",$str,3);
list($hostname,$port) = explode(':',$bits[1]);
list($username,$password) = explode(':',$bits[2]);
Edit to create what you need:
$str = '/server hostname:port username:password';
$bits = explode(" ",$str,3);
list($hostname,$port) = explode(':',$bits[1]);
$arr = array($hostname,$port,$bits[2]);
Solution 2:[2]
I wouldn't use regex for this, instead, try this
$str="/server hostname:port username:password";
$arr=explode(" ",$str);
$newarr=array(explode(":",$arr[1])[0],explode(":",$arr[1])[1],$arr[2]);
Here is a test for it
Solution 3:[3]
See explode function, it will do the job
Solution 4:[4]
Depending on the input format parse_url() could be an option.
Solution 5:[5]
$str = '/server hostname:port username:pa sword';
if(preg_match("|/server (.+):(.+) ([^:]+:.+)|", $str, $m)){
print_r($m);
}
Solution 6:[6]
I recommend preg_match()
. For best performance, use negated character classes or limited character ranges to allow the regex engine to perform greedy/possessive matching.
Code: (Demo)
$string = '/server localhost:3306 root:some pass with spaces & a : colon';
preg_match('~/server ([^:]+):(\d+) (.+)~', $string, $m);
array_shift($m); // remove the fullstring match
var_export($m);
Output:
array (
0 => 'localhost',
1 => '3306',
2 => 'root:some pass with spaces & a : colon',
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | scrblnrd3 |
Solution 3 | mr. Pavlikov |
Solution 4 | Lars Beck |
Solution 5 | Sabuj Hassan |
Solution 6 | mickmackusa |