简体   繁体   中英

How can I assign this as separate variables?

I have a string that looks like this "%one_two_three_four"

How can I set:

$a = "one" $b = "two" $c = "three" $d = "four"

Keeping it very simple you could do this

$in = "%one_two_three_four"

// remove the %
$t = str_replace('%', '', $in);

// split the string on each underscore into an array
$t = explode('_', $t);

// assign the array values to scalar variables
$a = $t[0];
$b = $t[1];
$c = $t[2];
$d = $t[3];

You can do this easily with

Example

sscanf('%one_two_three_four', '%%%[^_]_%[^_]_%[^_]_%s', $a, $b, $c, $d);

This will parse the string in the first argument according to the pattern in the second argument and assign any matched values to the remaining arguments.

The pattern explained:

  • %% is a literal %
  • %[^_] is everything but an underscore
  • _ is a literal underscore
  • %s is any string

You can also use

Example

list($a, $b, $c, $d) = preg_split(
    '#[%_]#', 
    '%one_two_three_four', 
    null, 
    PREG_SPLIT_NO_EMPTY
);

This will split the string by the given pattern and assign the results from the found matches. The fourth argument makes sure we only get non-empty results.

The pattern means: split by by underscore or percent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM