【问题标题】:How to separate a string and store in two variables in PHP [closed]如何在PHP中分隔字符串并存储在两个变量中[关闭]
【发布时间】:2013-09-25 12:25:15
【问题描述】:

我有字符串$ab="Hello_world.wav",我想将此字符串存储在两个变量中。一个是$a="Hello_world",另一个是$b=".wav"。 我应该如何使用字符串函数来获得它?

【问题讨论】:

标签: php


【解决方案1】:

从 PHP 5.3.0 起,Split 已被弃用。你不应该使用它(PHP manual)。相反,请使用explode:

$new_str_arr = explode('.', $ab);
$a = $new_str_arr[0];
$b = '.' . $new_str_arr[1];

【讨论】:

    【解决方案2】:

    尝试:

    $info = pathinfo('Hello_world.wav');
    
    var_dump($info);
    

    这给了你:

    array (size=4)
      'dirname' => string '.' (length=1)
      'basename' => string 'Hello_world.wav' (length=15)
      'extension' => string 'wav' (length=3)
      'filename' => string 'Hello_world' (length=11)
    

    所以:

    $a = $info['filename'];
    $b = '.' . $info['extension'];
    

    【讨论】:

    • 为什么要投反对票?看来这是最好的解决方案(我之前评论过)
    • +1 使用正确的功能
    • @jerdiggity 它适用于字符串 - 不是现有文件。我已经在我的文件系统中没有 fil 对其进行了测试。
    • LOL 是的...我意识到我在错误的上下文中说过,所以我删除了我的评论。但是,是的,你是对的。
    【解决方案3】:

    你也可以使用preg_split():

    $ab="Hello_world.wav";
    $matches = preg_split('/\./', $ab);
    $a = isset($matches[0]) ? $matches[0] : '';
    $b = isset($matches[1]) ? '.' . $matches[1] : '';
    // Print if you want by uncommenting the next line
    // print $a . ' ' . $b;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-27
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多