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
-
4Can you show an example of the variable? There are several different ways to split it, but it would depend on the delimiter.aynber– aynber2013-08-01 20:58:14 +00:00Commented Aug 1, 2013 at 20:58
-
2What have you tried? Additionally, this question doesn't have enough information to be answered correctly. What is your input variable's type? String, array?Dzhuneyt– Dzhuneyt2013-08-01 21:10:52 +00:00Commented Aug 1, 2013 at 21:10
Add a comment
|
5 Answers
<?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
?>
1 Comment
Daniele Vrut
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 ;)
Comments
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
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
list() is made for exactly this purpose.
<?php
list($artist, $title) = explode(' - ', $NowPlaying);
?>
3 Comments
Daniele Vrut
that's not correct. You use list with arrays not with strings.
Paul
No... list is made to do what it says in the link you posted.
Shylo Hana
Yeah - I shouldn't have skimmed the original question. Fixed it now.