1

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.

2 Answers 2

3

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);

Demo!

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, indeed, is a way cleaner than mine, but use of list sometimes take from readability. It's not the case here, contrary, here give readability.
Now I want to give best answer to both, damn.
@Carondimonio: Mine has demo and is shorter. cough :P
2

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.