简体   繁体   English

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

[英]combine 2 substr and 1 strpos in one line php

My string $podcast->title returns something like this :我的字符串 $podcast->title 返回如下内容:

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.但这没有用。

If your delimiter is always constant you can use explode , it's much easier, see example below.如果您的分隔符始终不变,您可以使用explode ,它更容易,请参见下面的示例。

$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你可以直接填充变量

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

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

Which will output哪个会输出

Artist Name
The Title

No whitespace :)没有空格:)

使用trim()命令:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM