1

I want to split a variable that I call for $ NowPlaying which contains the results of the current song. I would now like to share the following - so I get two new variables containing $ artist
$ title. Having searched and tried to find a solution, but have stalled grateful for a little assistance, and help

2
  • 4
    Can you show an example of the variable? There are several different ways to split it, but it would depend on the delimiter. Commented Aug 1, 2013 at 20:58
  • 2
    What have you tried? Additionally, this question doesn't have enough information to be answered correctly. What is your input variable's type? String, array? Commented Aug 1, 2013 at 21:10

5 Answers 5

5
<?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
?>
Sign up to request clarification or add additional context in comments.

1 Comment

If you use " - " for exploding var, instead of "-", you don't have to trim the results and it's a bit more safe (ie: with "Jay-Z"). Hope this helps ;)
1

Sounds like you're wanting to use explode()

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

Comments

1

Use php explode() function

$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];

Comments

0

I would usually do some thing like this:

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

I have looked at a couple split string questions and no one suggests using the php string functions. Is there a reason for this?

Comments

-1

list() is made for exactly this purpose.

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

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

3 Comments

that's not correct. You use list with arrays not with strings.
No... list is made to do what it says in the link you posted.
Yeah - I shouldn't have skimmed the original question. Fixed it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.