Grant
Grant

Reputation: 1337

combine 2 substr and 1 strpos in one line php

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

Answers (3)

Siffer
Siffer

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

Torchify
Torchify

Reputation: 134

Use trim() command:

$this_dj = trim(substr($podcast->title, 0, strpos($podcast->title, "-")));

Upvotes: 1

Alex Andrei
Alex Andrei

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

Related Questions