将字符串分成两部分:第一部分是标题,第二部分是使用php的章节



我一直在尝试一段时间找出如何分离这个字符串,但我不能弄清楚…因此,我有这个字符串:

$book = "1Thessalonians 2";

帖撒罗尼迦前书代表章节标题,后面的数字(2)代表章节。有没有办法把它们分开,这样我就有两个变量了?例如:

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

我想以@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
}
$book = "1Thessalonians 2";
$split_str = explode(" ", $book);
$title =  $split_str[0];
$chapter =  $split_str[1];
echo $title;
echo $chapter;

explode函数根据空格对字符串进行拆分,返回一个字符串数组,然后读取array。

最新更新