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

时间:2016-03-24 15:58:36

标签: php substr strpos

我的字符串$ podcast->标题返回如下内容:

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

但那没用。

3 个答案:

答案 0 :(得分: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

没有空格:)

答案 1 :(得分:1)

使用trim()命令:

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

答案 2 :(得分:0)

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

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