Reputation: 1337
My string $podcast->title returns something like this :
Artist Name - The Title
I'm using the following 2 lines of code :
$this_dj = substr($podcast->title, 0, strpos($podcast->title, "-"));
$this_dj = substr($this_dj, 0, -1);
The first line strips everything after (and including the "-") which leaves me with :
Artist Name
The second line removes the whitespace at the end.
My question is, can I combine these two lines into one line?
I've tried :
$this_dj = substr($podcast->title, 0, strpos($podcast->title, "-"), -1);
But that didn't work.
Upvotes: 2
Views: 1195
Reputation: 353
It would also work with your example, just move the substring end point:
$this_dj = substr($podcast->title, 0, strpos($podcast->title, "-") - 1);
Upvotes: 0
Reputation: 134
Use trim() command:
$this_dj = trim(substr($podcast->title, 0, strpos($podcast->title, "-")));
Upvotes: 1
Reputation: 7283
If your delimiter is always constant you can use explode
, it's much easier, see example below.
$string = 'Artist Name - The Title';
$array = explode(' - ', $string);
print_r($array);
Will output
Array
(
[0] => Artist Name
[1] => The Title
)
And using list
you can populate variables directly
list($artist,$song) = explode(' - ', $string);
print $artist . PHP_EOL;
print $song . PHP_EOL;
Which will output
Artist Name
The Title
No whitespace :)
Upvotes: 1