$string = 'Some string';
$pos = 5;
...??...
$begging // == 'Some s';
$end // == 'tring';
Run Code Online (Sandbox Code Playgroud)
在给定位置将字符串分成两部分的最佳方法是什么?
Gum*_*mbo 32
您可以使用substr
获取两个子字符串:
$str1 = substr($str, 0, $pos);
$str2 = substr($str, $pos);
Run Code Online (Sandbox Code Playgroud)
如果省略第三个参数长度,则substr
取其余的字符串.
但要获得结果,您实际上需要添加一个$pos
:
$string = 'Some string';
$pos = 5;
$begin = substr($string, 0, $pos+1);
$end = substr($string, $pos+1);
Run Code Online (Sandbox Code Playgroud)
rub*_*ots 22
正则表达式解决方案(如果你进入它):
...
$string = 'Some string xxx xxx';
$pos = 5;
list($beg, $end) = preg_split('/(?<=.{'.$pos.'})/', $string, 2);
echo "$beg - $end";
Run Code Online (Sandbox Code Playgroud)
问候
RBO