【问题标题】:To explode the string based on the special characters in Php根据 PHP 中的特殊字符来分解字符串
【发布时间】:2015-07-08 10:11:08
【问题描述】:

我有一个字符串:

xyz.com?username="test"&pwd="test"@score="score"#key="1234"

输出格式:

array (
    [0] => username="test"
    [1] => pwd="test"
    [2] => score="score"
    [3] => key="1234"
)

【问题讨论】:

  • 你试过了吗?
  • preg_split ("/\?|&|@|#/", $string)

标签: php special-characters explode


【解决方案1】:

这应该适合你:

只需将preg_split()character class 一起使用,其中包含所有分隔符。最后只需使用array_shift() 删除第一个元素。

<?php

    $str = 'xyz.com?username="test"&pwd="test"@score="score"#key="1234"';

    $arr = preg_split("/[?&@#]/", $str);
    array_shift($arr);

    print_r($arr);

?>

输出:

Array
(
    [0] => username="test"
    [1] => pwd="test"
    [2] => score="score"
    [3] => key="1234"
)

【讨论】:

    【解决方案2】:

    您可以将preg_split 函数与正则表达式模式一起使用,包括所有那些定界特殊字符。然后删除数组的第一个值并重置键:

    $s = 'xyz.com?username="test"&pwd="test"@score="score"#key="1234"';
    $a = preg_split('/[?&@#]/',$s);
    unset($a[0]);
    $a = array_values($a);
    
    print_r($a);
    

    输出:

    Array ( 
    [0] => username="test" 
    [1] => pwd="test" 
    [2] => score="score" 
    [3] => key="1234" 
    ) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 2012-09-05
      • 2020-05-18
      相关资源
      最近更新 更多