Php split a string to to string - php

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

<?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
?>

Sounds like you're wanting to use explode()
http://php.net/manual/en/function.explode.php

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

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?

list() is made for exactly this purpose.
<?php
list($artist, $title) = explode(' - ', $NowPlaying);
?>
http://php.net/manual/en/function.list.php

Related

How to explode the string back from the second or third string delimiter?

How can I get the 800-555 from this 800-555-5555 with explode()?
Here is a good example:
$rawPhoneNumber = "800-555-5555";
$phoneChunks = explode("-", $rawPhoneNumber);
First chunk = $phoneChunks[0]; //800
Second chunk = $phoneChunks[1]; //555
Third Chunk chunk = $phoneChunks[2]; //5555
But how can I get the 800-555?
Okay, I see, here need more comment... So, this is only an example... In real I add a word (now $word) to string delimiter and my string is a full article... I want that, if this word second time published in the article, with str_word_count() will count, how many characters was in the text to the second (or third, if I want that) $word...
So I want that, I get the string from the second "hit" to back.
Okay, here is a more obvious example:
$text = oh my god, thank you the lot of downvotes, geniuses *.*
$explode = explode(",", $text);
$whatiwant = $explode?? // I WANT THE STRING FROM THE SECOND "," TO BACK
So I want that $whatiwant = oh my god, thank you the lot of downvotes
Implode, explode and array_slice.
I use array_slice because that makes the function more dynamic.
Now you can just set the $items to get the number of items you want.
If you set a negative value it counts backwards.
$delim = ",";
$items =2;
$text = "oh my god, thank you the lot of downvotes, geniuses *.*";
$whatiwant = implode($delim, array_slice(explode($delim, $text),0,$items));
Echo $whatiwant;
https://3v4l.org/KNSC4
You could also have an start variable to make the start position dynamic.
https://3v4l.org/XD0NV
Doing concatenation of already generated array's indexes is the simple way for you.
Sample Code
echo $phoneChunks[0]."-".$phoneChunks[1];
This is working for me:
$rawPhoneNumber = "800-555-5555";
$phoneChunks = explode("-", $rawPhoneNumber);
$first_chunk = $phoneChunks[0]; //800
$second_chunk = $phoneChunks[1]; //555
$third_chunk_chunk = $phoneChunks[2]; //5555
$portion_array = array($first_chunk, $second_chunk);
echo implode("-",$portion_array);
Output:
800-555

How to use explode and get first element in one line in PHP?

$beforeDot = explode(".", $string)[0];
This is what I'm attempting to do, except that it returns syntax error. If there is a workaround for a one liner, please let me know. If this is not possible, please explain.
The function array dereferencing was implemented in PHP 5.4, so if you are using an older version you'll have to do it another way.
Here's a simple way to do it:
$beforeDot = array_shift(explode('.', $string));
You can use list for this:
list($first) = explode(".", "foo.bar");
echo $first; // foo
This also works if you need the second (or third, etc.) element:
list($_, $second) = explode(".", "foo.bar");
echo $second; // bar
But that can get pretty clumsy.
Use current(), to get first position after explode:
$beforeDot = current(explode(".", $string));
Use array_shift() for this purpose :
$beforeDot = array_shift(explode(".", $string));
in php <= 5.3 you need to use
$beforeDot = explode(".", $string);
$beforeDot = $beforeDot[0];
2020 : Google brought me here for something similar.
Pairing 'explode' with 'implode' to populate a variable.
explode -> break the string into an array at the separator
implode -> get a string from that first array element into a variable
$str = "ABC.66778899";
$first = implode(explode('.', $str, -1));
Will give you 'ABC' as a string.
Adjust the limit argument in explode as per your string characteristics.
You can use the limit parameter in the explode function
explode($separator, $str, $limit)
$txt = 'the quick brown fox';
$explode = explode(' ', $txt, -substr_count($txt, ' '));
This will return an array with only one index that has the first word which is "the"
PHP Explode docs
Explanation:
If the limit parameter is negative, all components except the last
-limit are returned.
So to get only the first element despite the number of occurences of the substr you use -substr_count

How to get part of string from the end in PHP?

I am making application where I receive a string from user. The string is concatenated with - character between them. First part of string contains alphabetic data whereas later part contains integers or floating point numbers. For example: A string might be 3 Cups Tea-5.99.I want to get the later part of string 5.99 separated by - character. How to do that? I know about PHP substr() function but that takes fixed characters to retrieve substring from. But in this case the later part will not be fixed. For example: 2 Jeans-65.99. In this case I would need last 4 characters meaning that I can't use substr() function.
Anybody with solution?
I know I would need to apply regex but I am completely novice in Regex.
Waiting for your help.
Thanks!
Simply
$result = explode('-', $string)[1];
For PHP<5.4 you'll have to use temporary variable:
$data = explode('-', $string);
$result = $data[1];
Edit
As mentioned in comments, if there is more than 1 part, that will be:
$result = array_pop(explode('-', $string));
$bits = explode('-', $inputstring);
echo $bits[1];
You can use substr() with strpos():
$str = '3 Cups Tea-5.99';
echo substr($str, strpos($str, "-") + 1);
Output:
5.99
Demo!
If data will be like this: "1-Cup tea-2.99", then
$data = "1-Cup tea-2.99";
$data = explode('-', $string);
$result = $data[count($data)-1];

Shortcut for: $foo = explode(" ", "bla ble bli"); echo $foo[0]

is there a way to get the n-th element of a splitted string without using a variable?
My PHP code always looks like this:
$foo = explode(" ", "bla ble bli");
echo $foo[0];
Is there a shorter way maybe like in Python?
print "bla ble bli".split(" ")[0]
Thanks in advance.
This is what people should be using instead of explode most of the time:
$foo = strtok("bla ble bli", " ");
It cuts off the first string part until the first " ".
If you can't let go of explode, then the closest idiom to accomplish [0] like in Python is:
$foo = current(explode(...));
If it's not just the first element, then it becomes a tad more cumbersome:
$foo = current(array_slice(explode(...), 2)); // element [2]
(Not really an answer per se -- others did answer pretty well)
This is one of the features that should arrive with one of the next versions of PHP (PHP 5.4, maybe).
For more informations, see Features in PHP trunk: Array dereferencing -- quoting one of the given examples :
<?php
function foo() {
return array(1, 2, 3);
}
echo foo()[2]; // prints 3
?>
try this:
its one line:
<?php
echo (($f=explode(" ", "bla ble bli"))?$f[0]:'');
?>
result here:
http://codepad.org/tnhbpYdd
Why not just do:
function splode($string, $delimiter, $index){
$r = explode($delimiter, $string);
return $r[$index];
}
I use like a hojillion little functions like this.
With only one expression I can think of:
echo list($a) = explode(' ', 'a b c') ? $a : '';
echo list($_, $b) = explode(' ', 'a b c') ? $b : '';
Not as far as I know although you could define a function and use that.
function firstWord($string) {
$foo = explode(" ", $string);
return $string;
}
I don't know of a way to do what you want, even though I've wanted to do the same thing many times before. For that specific case you could do
$bar = substr($foo, 0, strpos($foo, " "));
which stops there being one extra variable, but isn't exactly what you wanted.
The following is probably the cleanest way I can think of doing what OP has requested. It defines a function, but no variables of it's own and it'll get the job done for just about any situation:
function at(&$arr, &$pos) { return $arr[$pos]; }
Example usage:
echo at( explode('|', 'a|b|c|d'), 1 ); // Outputs 'b'
The function is a single line of code and wouldn't be hard to commit to memory. If you're only using it once, you can define it in the local scope of where it'll be used to minimize code clutter.
As a slight added benefit, because the function does no checks on $arr or $pos, it'll throw all the same errors that it would if you tried to access a non-existent index for an array, or will even return the individual characters in a string or items in a key-value paired array.
close. the right track is making a function or method for something that gets repeated.
function extract_word($input, $index) {
$input = explode(' ', $input);
return $input[$index];
}
add a third argument of $separater = ' ' if you may have different word separaters.

sub string replacment in PHP

I have a string like:
$string = "/physics/mechanics/vectors/P-M-C (1).doc";
I want to get like this:
"/physics/mechanics/vectors/1-P-M-C (1).doc";
Please note that "1-" is added just before P in the original string.
Is it possible in PHP?
How the function in PHP should be used?
#fawad:Here's a sample to get you started --
$oldstring = "/physics/mechanics/vectors/P-M-C (1).doc";
$parts = explode("/", $oldstring);
$file = $parts[count($parts) - 1];
$newstring = str_replace($file, "1-" . $file, $oldstring);
Take a look at explode() and join() for this. :)

Categories