将字符串按给定位置一分为二 [英] separate string in two by given position

查看:120
本文介绍了将字符串按给定位置一分为二的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

...??...

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

按给定位置将字符串一分为二的最佳方法是什么?

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

推荐答案

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

You can use substr to get the two sub-strings:

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

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

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

但是要获得结果,您实际上需要在$pos中添加一个:

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

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

这篇关于将字符串按给定位置一分为二的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆