簡體   English   中英

將 2 個 substr 和 1 strpos 合並在一行 php 中

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

我的字符串 $podcast->title 返回如下內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM