【问题标题】:Separate string in two parts: firts part is the title, the second is the chapter using php将字符串分成两部分:第一部分是标题,第二部分是使用 php 的章节
【发布时间】:2021-01-29 11:38:36
【问题描述】:

我已经尝试了一段时间来弄清楚如何分隔这个字符串,但我无法弄清楚......所以,我有这个字符串:

$book = "1Thessalonians 2";

嗯,1Thessalonians 代表章节标题,后面的数字 (2) 代表章节。有没有办法将它们分开,所以我可以有两个变量? 例如:

$title = "1Thessalonians";
$chapter = "2";

【问题讨论】:

  • 你能再举一些例子吗?最后总是有一个数字吗?里面没有空格?

标签: php string variables split numbers


【解决方案1】:

我想以@Rabnawaz 的回答为基础。我假设标题本身可以有空格。解决这个问题:

$splitStr = explode(" ", $book);
$title = "";
$chapter = "";
if(is_array($splitStr)){
 $chapter = $splitStr[count($splitStr) - 1]; // The last string
 unset($splitStr[count($splitStr) - 1]; // Remove the chapter from array
 $title = implode(" ", $splitStr); // Glue the string back together without the chapter
}

【讨论】:

  • 工作就像一个魅力。非常感谢!
【解决方案2】:
$book = "1Thessalonians 2";

$split_str = explode(" ", $book);
$title =  $split_str[0];
$chapter =  $split_str[1];

echo $title;
echo $chapter;

explode函数根据空格分割字符串,返回一个字符串数组,然后就可以读取数组了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多