用分隔符将字符串分成两半

发布于 2024-10-04 02:12:00 字数 312 浏览 5 评论 0原文

我正在尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

踏雪无痕 2024-10-11 02:12:00

获取数组:

$array = explode('|', $str);

或者直接获取两部分:

list($left, $right) = explode('|', $str);

参见 explode PHP手册中的

To get an array:

$array = explode('|', $str);

Or to directly get two parts:

list($left, $right) = explode('|', $str);

See explode in the PHP manual.

孤云独去闲 2024-10-11 02:12:00

PHP 采用了 C 语言函数 sscanf() 来解析可预测格式的字符串,并且它能够将数值转换为整数/浮点类型(其中 explode()自己做不到)。

根据您的需要进行一些实现:(演示

  1. 返回数组:

    <前><代码>var_export(
    sscanf($str, '%[^|]|%f')
    );

    输出:

    <前><代码>数组(
    0 => 'blahblah1323r8b',
    1 => 7.45,

  2. 创建单个变量:

    sscanf($str, '%[^|]|%f', $left, $right);
    var_dump($左, $右);
    

    输出:

    <前><代码>字符串(15)“blahblah1323r8b”
    浮动(7.45)

  3. 创建关联数组:

    [$key, $result[$key]] = sscanf($str, '%[^|]|%f');
    var_export($结果);
    

    输出:

    <前><代码>数组(
    '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 (which explode() can't do by itself).

A few implemenations depending on your needs: (Demo)

  1. return an array:

    var_export(
        sscanf($str, '%[^|]|%f')
    );
    

    output:

    array (
      0 => 'blahblah1323r8b',
      1 => 7.45,
    )
    
  2. create individual variables:

    sscanf($str, '%[^|]|%f', $left, $right);
    var_dump($left, $right);
    

    output:

    string(15) "blahblah1323r8b"
    float(7.45)
    
  3. create an associative array:

    [$key, $result[$key]] = sscanf($str, '%[^|]|%f');
    var_export($result);
    

    output:

    array (
      'blahblah1323r8b' => 7.45,
    )
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文