php 按给定位置将字符串分成两部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3449348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:48:45  来源:igfitidea点击:

separate string in two by given position

phpstring

提问by Qiao

$string = 'Some string';
$pos = 5;

...??...

$begging // == 'Some s';
$end // == 'tring';

What is the best way to separate string in two by given position?

按给定位置将字符串分成两部分的最佳方法是什么?

回答by Gumbo

You can use substrto get the two sub-strings:

您可以使用substr来获取两个子字符串:

$str1 = substr($str, 0, $pos);
$str2 = substr($str, $pos);

If you omit the third parameter length, substrtakes the rest of the string.

如果省略第三个参数length,则substr采用字符串的其余部分。

But to get your result you actually need to add one to $pos:

但要得到你的结果,你实际上需要添加一个到$pos

$string = 'Some string';
$pos = 5;
$begin = substr($string, 0, $pos+1);
$end = substr($string, $pos+1);

回答by rubber boots

Regex solution (if you are into it):

正则表达式解决方案(如果你喜欢的话):

...
$string = 'Some string xxx xxx';
$pos = 5;

list($beg, $end) = preg_split('/(?<=.{'.$pos.'})/', $string, 2);

echo "$beg - $end";

Regards

问候

rbo

红包

回答by timmyc

How about substr()?

substr() 怎么样?

$string = 'Some string';
$pos = 5;

$beginning = substr($string, 0, $pos);
$end = substr($string, $pos);

回答by Sarfraz

What is the best way to separate string in two by given position?

按给定位置将字符串分成两部分的最佳方法是什么?

If i understand you correctly, you can do:

如果我理解正确,你可以这样做:

$str = 'hello world';
$pos = 5;

$separated_str = substr($str, $pos);
echo $separated_str;

Result:

结果:

world

This depends on the structure of your string as there are other ways also to split the string.

这取决于字符串的结构,因为还有其他方法可以拆分字符串。

回答by AWippler

Wordwrapworks better in my opinion.

我认为Wordwrap效果更好。

$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");
echo $newtext;

The above example will output:

上面的例子将输出:

The quick brown fox<br />
jumped over the lazy<br />
dog.

Another example:

另一个例子:

$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", true);

echo "$newtext\n";

The above example will output:

上面的例子将输出:

A very
long
wooooooo
ooooord.

回答by CoffeDeveloper

I was searching for a fast a way to split a string at a given position.

我正在寻找一种在给定位置快速拆分字符串的方法。

Why a given position? Usually what you need is to split against a character (I think you searched by position because the explode function would split the string in too much pieces):

为什么是给定的职位?通常你需要的是对一个字符进行拆分(我认为你是按位置搜索的,因为爆炸函数会将字符串分成太多部分):

My solution was finally:

我的解决方案最终是:

$string = "hello world my dear";
list ($first, $remaining ) = split (' ', $string, 2); //limit to 2 pieces
echo $first; //"hello";
echo $remaining; //"world my dear";

Notice that I dropped the use of "position" (I was using "substr" to get it).

请注意,我放弃了“位置”的使用(我使用“substr”来获取它)。

Given that your need for "position" was not really necessary, my solution is the fastest among all others above and does not have multi-byte issues. Also I think it is much easier to read.

鉴于您对“位置”的需求并不是真正必要的,我的解决方案是上述所有解决方案中最快的,并且没有多字节问题。此外,我认为它更容易阅读。

Unluckily that function is deprecated in last PHP, you can use it if you have old PHP or you can use preg_split. I was not very happy of that because the only way to achieve same functionality is abusing regex. In case you cannot use splitthe fastest alternative is:

不幸的是,该函数在最后一个 PHP 中已被弃用,如果您有旧的 PHP,您可以使用它,或者您可以使用 preg_split。我对此不太满意,因为实现相同功能的唯一方法是滥用正则表达式。如果您不能使用split最快的替代方法是:

$string = "hello world my dear";
list ($first, $remaining ) =  preg_split('/\s+/', $string, 2);

wich is much faster than @rubber answer and does not use position at all.

这比@rubber 答案要快得多,并且根本不使用位置。

Reference: Split documentation

参考: 拆分文档

回答by CJ Dennis

<?php
$string = 'Some string';
$pos = 6;
$number_of_pieces = 2;
list($beginning, $end) = split_into_pieces($string, $pos, $number_of_pieces);
// $beginning === 'Some s'; $end === 'tring'

function split_into_pieces($string, $length, $limit = 0) {
  --$length;
  return preg_split("/(?<=^..{{$length}}|(?!^)\G.{{$length}})/", $text, $limit);
}
  • $stringis the string to split
  • $lengthis the size of each piece in Unicode code-points (or ASCII characters if not using the UTF-8 option, see below). Any value less than 1will return the entire input string as a single piece
  • $limitis the maximum number or pieces, or 0for unlimited. The final piece will contain the remainder of the string and might be longer or shorter than $length
  • $string是要拆分的字符串
  • $length是 Unicode 代码点(或 ASCII 字符,如果不使用 UTF-8 选项,请参见下文)中的每个片段的大小。任何小于的值1都将作为一个整体返回整个输入字符串
  • $limit是最大数量或件数,或0为无限。最后一段将包含字符串的其余部分,可能长于或短于$length

The regex that is doing the magic is using a positive look-behind (?<=... ). It looks for ^, which is the start of the string, |or if it's not at the beginning of the string (?!^)it looks for \G, which is the position of the previous match. .is any character, {n}is repeated ntimes, where nis {$length}. When using \G, it adds an extra character for some reason, which is why there's the line --$length;and why the first match has an extra .to search for an extra code-point, which is not usually allowed in look-behinds. I think the zero-width assertions ^and \Gare anchoring the pattern, allowing different lengths in the look-behind.

正在发挥魔力的正则表达式是使用正向后视(?<=... )。它查找^,这是字符串的开头,|或者如果它不在字符串的开头,(?!^)则查找\G,这是前一个匹配项的位置。.是任何字符,{n}重复n次,其中n{$length}。使用时\G,由于某种原因,它会添加一个额外的字符,这就是为什么存在该行--$length;以及为什么第一个匹配项有额外.的搜索额外代码点的原因,这通常在后视中是不允许的。我认为零宽度断言^\G正在锚定模式,允许在后视中使用不同的长度。

The extra {and }around $lengthare necessary to stop the regex braces being interpreted as an escaped PHP variable. /suare the regex options. The /soption says allow .to match newline characters. The /uoption says to match Unicode code-points encoded as UTF-8 (remove uif you are parsing strings that are non-UTF-8 compliant).

extra{}around$length是阻止正则表达式大括号被解释为转义的 PHP 变量所必需的。/su是正则表达式选项。该/s选项表示允许.匹配换行符。该/u选项表示匹配编码为 UTF-8 的 Unicode 代码点(u如果您正在解析不符合 UTF-8 的字符串,请删除)。

回答by Faisal

<?php
Function Splp($S,...$A){ #Split At Positions 
    $k = 0;
    $R = [];
    $A[] = Strlen($S);
    Foreach($A As $a){
        $R[] = Substr($S,$k,$a-$k);
        $k = $a;
    }
    Return $R;}

$string = 'Some string';
$pos1 = 5;
$pos2 = 7;
[$Start,$Mid,$End] = Splp($string,$pos1,$pos2);
echo $Start,', ',$Mid,', ',$End; #  Some , st, ring
?>