Search code examples
phpsubstrstrpos

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.


Solution

  • It would also work with your example, just move the substring end point:

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