【问题标题】:combine 2 substr and 1 strpos in one line php在一行php中结合2个substr和1个strpos
【发布时间】:2016-03-24 15:58:36
【问题描述】:

我的字符串 $podcast->title 返回类似这样的内容:

Artist Name - The Title

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

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

但这没有用。

【问题讨论】:

  • 如果你想在最后删除空格,最好的方法是使用trim()
  • 我可以在最后添加吗?
  • 像这样:trim(substr($podcast->title, 0, strpos($podcast->title, "-")));

标签: php substr strpos


【解决方案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

没有空格:)

【讨论】:

  • 虽然严格来说这不是我问题的答案,但它很棒。我打算这样做。我将不得不接受其他答案之一,因为它们与问题更直接相关,但非常感谢 Alex!
【解决方案2】:

使用trim() 命令:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 是的,这行得通,我还包括一个额外的逗号。谢谢西弗!
    猜你喜欢
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2013-09-20
    • 2021-07-22
    相关资源
    最近更新 更多