Synergy
Synergy

Reputation: 13

Get value after a specified word

I have a function with a parameter to pass.

For example:

$this->avatar->getAvatar('size=s/user=Synergy');

Now I want to explode the string at "/" and get the key for example "user" and the value "Synergy". And this for every explode.

Here is my function:

public function getAvatar($params)
  {
    $this->params = explode('/', $params);

    if(strpos($this->params, 'size=') !== false) {
      $this->size = // how to get value after "=" ??
    }

    if(strpos($this->params, 'user=') !== false) {
      $this->user = // how to get value after "=" ??
    }
  }

Upvotes: 1

Views: 56

Answers (3)

keversc
keversc

Reputation: 346

if you replace / by & and parse the string with the php method parse_str :

$infos = array();
parse_str(str_replace('/', '&', $params), $infos);

$infos now looks like:

array(2) {
  ["size"]=>  string(1) "s"
  ["user"]=> string(4) "Synergy"
}

Finish by :

$this->size = $infos['size'];
$this->user = $infos['user'];

Upvotes: 0

Makesh
Makesh

Reputation: 1234

Try this:

<?php

$var = 'size=s3435/user=Synergy';
$temp = explode('/', $var);
//Fetch size
$pos = strpos($temp[0], '=');
echo substr($temp[0], 0, $pos); //key
echo substr($temp[0], $pos+1);  //value

//Fetch user
$pos = strpos($temp[1], '=');
echo substr($temp[1], 0, $pos);
echo substr($temp[1], $pos+1);
?>

Avail @ https://ideone.com/BxqooK

Note: Use loop if you have many key-value pairs separated by /

Upvotes: 0

Pupil
Pupil

Reputation: 23978

Use explode()

$var = 'size=s/user=Synergy';
$temp = explode('user=', $var);
$username = ! empty($temp[1]) ? $temp[1] : '';

Upvotes: 1

Related Questions