我有这样的绳子 -
$existingStr = "Test# 123456 Opened by System";
我想要像这样的 3 个不同部分的字符串 -
1st part : Test#
2nd part : 123456
3rd part : rest of the part
因此,首先我得到哈希位置,然后我从增量哈希位置值中寻找空间位置,但它没有给我下一个空间位置。
代码 -
echo $existingStr."<br>";
$strhashPos = strpos($existingStr,"#");
echo $strhashPos."<br>";
$strincementhashPos = $strhashPos + 1;
echo $strincementhashPos ."<br>";
$strspacePos = strpos($existingStr,' ',$strincementhashPos);
echo $strspacePos."<br>";
$tempWOId = $strspacePos-$strincementhashPos;
echo $tempWOId."<br>";
$strFirstPart = substr($existingStr,0,$strincementhashPos);
echo $strFirstPart."<br>";
$strSecondPart = substr($existingStr,$strincementhashPos,$tempWOId);
echo $strSecondPart."<br>";
$strThirdPart = substr($existingStr,$strspacePos,-1);
echo $strThirdPart."<br>";
因此它给了我错误的 $strSecondPart ...有人可以建议我获得下一个空间位置有什么问题吗?还建议一些优化或替代方案...
explode()
函数
返回一个字符串数组,每个字符串都是字符串在字符串分隔符形成的边界上分割而成的子字符串。
即:
php > $existingStr = "Test# 123456 Opened by System";
php > $strToArr = explode(' ', $existingStr);
php > $strFirstPart = $strToArr[0];
php > echo $strFirstPart . "<br />";
Test#<br />
php > $strSecondPart = $strToArr[1];
php > echo $strSecondPart . "<br />";
123456<br />
array_slice()
和 implode()
函数:
php > $strThirdPart = implode(" ", array_slice($strToArr, 2));
php > echo $strThirdPart;
Opened by System
希望有帮助。
编辑
遵循@Evert评论:
explode()
函数可以采用第三个参数来定义限制。这提供了一个很好的快捷方式!
即:
$existingStr = "Test# 123456 Opened by System";
print_r(explode(' ', $existingStr, 3));
输出:
数组 ( [0] => 测试# [1] => 123456 [2] => 系统打开 )
<?php
$existingStr = "Test# 123456 Opened by System";
$items = explode(' ', $existingStr);
$first = $items[0];
$second = $items[1];
unset($items[0]);
unset($items[1]);
$third = join($items);
echo $first."\n";
echo $second."\n";
echo $third."\n";
这是结果:
localhost:~$ php -f aaaa
Test#
123456
OpenedbySystem
explode()
对于此任务来说并不理想,因为它会创建比需要的更多的元素。 相反,请使用 preg_split()
将输入分为三个所需的部分。
代码:(演示)
$existingStr = "Test# 123456 Opened by System";
var_export(
preg_split(
'/#\K (\S+) /',
$existingStr,
2,
PREG_SPLIT_DELIM_CAPTURE
)
);
输出:
array (
0 => 'Test#',
1 => '123456',
2 => 'Opened by System',
)
也许不直观的是,可以使用
2
的“子字符串限制”值,但输出包含 3 个元素(因为捕获的分隔符不是限制计算的一部分)。