Reputation: 111
Sorry if this is a newbie question. Lets say I have this string (the values name and server can change): Also I forgot to say that I know the length of 'something' .
$str='something-name:Jon,server:localhost'
Now I must pull the values: 'Jon' and 'localhost' and put them in variables.
What I am doing now:
if ((strpos($str, 'something')) !== false){
$par_name = strpos($str, 'name:');
if ($par_name !== false){
$name = substr($n, 20);
}
}
Now:
$name == 'Jon,server:localhost'
Instead I need to get only the name and the after the server substring.
$name == 'Jon'
$server == 'localhost'
I guess I have to find the exact value for the third parameter of substr. I dont know.
Thank you for your responses.
Upvotes: 1
Views: 81
Reputation: 76666
You can do this easily with explode()
. Split the string with comma as the delimiter, split the parts with colon as the delimiter, and grab the part before the colon in both the parts:
$str='something-name:Jon,server:localhost';
list($part1, $part2) = explode(',', $str);
list(,$name) = explode(':', $part1);
list(,$server) = explode(':', $part2);
Upvotes: 3
Reputation: 1557
It's just a fast example of how you could achieve this:
$str='something-name:Jon,server:localhost'
$explode = explode(',', $str);
$explodePart1 = explode(':', $explode[0]);
$explodePart2 = explode(':', $explode[1]);
$name = explodePart1[1]
$server = explodePart2[1];
Upvotes: 2