strpos 需要其他东西吗

问题描述 投票:0回答:3

我有这样的绳子 -

$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 ...有人可以建议我获得下一个空间位置有什么问题吗?还建议一些优化或替代方案...

php string
3个回答
1
投票

你可以使用 php

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] => 系统打开 )


0
投票
<?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

0
投票

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 个元素(因为捕获的分隔符不是限制计算的一部分)。

© www.soinside.com 2019 - 2024. All rights reserved.