【问题标题】:Php split a string to to stringphp将字符串拆分为字符串
【发布时间】:2013-08-01 20:57:19
【问题描述】:

我想拆分一个我为 $ NowPlaying 调用的变量,其中包含当前歌曲的结果。我现在想分享以下内容 - 所以我得到了两个包含 $artist
$title 的新变量。已经搜索并试图找到解决方案,但对于一点帮助和帮助表示感谢

【问题讨论】:

  • 你能举一个变量的例子吗?有几种不同的拆分方式,但具体取决于分隔符。
  • 你试过什么?此外,这个问题没有足够的信息来正确回答。您的输入变量的类型是什么?字符串、数组?

标签: php split


【解决方案1】:
<?php
// Assuming $NowPlaying is something like "J. Cole - Chaining Day" 
// $array = explode("-", $NowPlaying); //enter a delimiter here, - is the example
$array = explode(" - ", $NowPlaying); //DJHell pointed out this is better
$artist = $array[0]; // J. Cole
$song = $array[1]; // Chaining Day
// Problems will arise if the delimiter is simply (-), if it is used in either 
// the song or artist name.. ie ("Jay-Z - 99 Problems") so I advise against 
// using - as the delimiter. You may be better off with :.: or some other string
?>

【讨论】:

  • 如果你使用“-”来爆炸var,而不是“-”,你不必修剪结果,它更安全一点(即:使用“Jay-Z”)。希望这会有所帮助;)
【解决方案2】:

听起来你想使用explode()

http://php.net/manual/en/function.explode.php

【讨论】:

    【解决方案3】:

    使用php explode()函数

    $str_array = explode(' - ', $you_song);
    // then you can get the variables you want from the array
    $artist = $str_array[index_of_artist_in_array];
    $title  = $str_array[index_of_title_in_array];
    

    【讨论】:

      【解决方案4】:

      我通常会这样做:

      <?php    
      $input = 'Your - String';
      $separator = ' - ';
      $first_part = substr($input, 0, strpos($input, $separator));
      $second_part = substr($input, (strpos($input, $separator) + strlen($separator)), strlen($input));
      ?>
      

      我看过几个拆分字符串的问题,没有人建议使用 php 字符串函数。这是有原因的吗?

      【讨论】:

        【解决方案5】:

        list() 正是为此目的而制作的。

        <?php
          list($artist, $title) = explode(' - ', $NowPlaying);
        ?>
        

        http://php.net/manual/en/function.list.php

        【讨论】:

        • 这是不正确的。您将列表与数组一起使用,而不是与字符串一起使用。
        • 不...列表是按照您发布的链接中所说的内容制作的。
        • 是的 - 我不应该略过最初的问题。现在修好了。
        猜你喜欢
        • 1970-01-01
        • 2020-05-18
        • 2015-12-28
        • 2012-02-22
        • 2019-04-16
        • 1970-01-01
        • 2011-11-25
        相关资源
        最近更新 更多