在一行中合并 2 个 substr 和 1 个 strpos php

combine 2 substr and 1 strpos in one line php

我的字符串 $podcast->title returns 是这样的:

Artist Name - The Title

我正在使用以下两行代码:

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

第一行删除了后面的所有内容(包括“-”),剩下的是:

Artist Name 

第二行去掉末尾的空格。

我的问题是,我可以将这两行合并为一行吗?

我试过了:

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

但这没有用。

如果您的定界符始终不变,您可以使用 explode,这会容易得多,请参见下面的示例。

$string = 'Artist Name - The Title';

$array = explode(' - ', $string);

print_r($array);

会输出

Array
(
    [0] => Artist Name
    [1] => The Title
)

并且使用 list 您可以直接填充变量

list($artist,$song) = explode(' - ', $string);

print $artist . PHP_EOL;
print $song . PHP_EOL;

哪个会输出

Artist Name
The Title

没有空格 :)

使用trim()命令:

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

它也适用于您的示例,只需移动子字符串结束点:

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