用分隔符将字符串分成两半
我正在尝试在 PHP 中拆分一个字符串,但是它不像在 C# 中那么容易,它似乎有点混乱...
我有一个字符串,看起来像这样:
blahblah1323r8b|7.45
并且我希望能够像这样访问分割结果:
$var = split_result['leftside'];
$var = split_result['rightside'];
Is this easy to do in PHP?我试图找到一些好的例子,但我见过的例子似乎不是我想要做的,而且有点过于复杂。
I am trying to split a string in PHP however it's not as easy as it is in C#, it seems to be a tad bit messy...
I have a string, which looks something like this:
blahblah1323r8b|7.45
and I would like to be able to access the results of the split like this:
$var = split_result['leftside'];
$var = split_result['rightside'];
Is this easy to do in PHP? I'm trying to find some good examples, but the ones I've seen seem to be not what I'm trying to do, and are a little over complicated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
获取数组:
或者直接获取两部分:
参见
explode
PHP手册中的。To get an array:
Or to directly get two parts:
See
explode
in the PHP manual.PHP 采用了 C 语言函数
sscanf()
来解析可预测格式的字符串,并且它能够将数值转换为整数/浮点类型(其中explode()
自己做不到)。根据您的需要进行一些实现:(演示)
返回数组:
<前><代码>var_export(
sscanf($str, '%[^|]|%f')
);
输出:
<前><代码>数组(
0 => 'blahblah1323r8b',
1 => 7.45,
)
创建单个变量:
输出:
<前><代码>字符串(15)“blahblah1323r8b”
浮动(7.45)
创建关联数组:
输出:
<前><代码>数组(
'blahblah1323r8b'=> 7.45,
)
PHP has adopted a C language function
sscanf()
for parsing a predictably formatted string AND it has the capability of casting the numeric values as integer/float types (whichexplode()
can't do by itself).A few implemenations depending on your needs: (Demo)
return an array:
output:
create individual variables:
output:
create an associative array:
output: