V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
mantis
V2EX  ›  PHP

求解,字符串按特殊字符进行拆分

  •  
  •   mantis · Sep 19, 2022 · 2144 views
    This topic created in 1322 days ago, the information mentioned may be changed or developed.

    字符串:

    $str = "两个人的小森林有*2*个热点*爆*词你还未看(217054)";
    
    

    进行拆分,两个xx*中间的标记为 type=2,其他标记 type=1 ,期望结果如下:

    [
        {
            "type": 1,
            "text": "两个人的小森林有"
        },
        {
            "type": 2,
            "text": "2",
        },
        {
            "type": 1,
            "text": "个热点",
        },
        {
            "type": 2,
            "text": "爆",
        },
        {
            "type": 1,
            "text": "词你还未看(217054)"
        }
    ]
    
    

    求解,php 如何实现?

    eason1874
        1
    eason1874  
       Sep 19, 2022
    ?又来问,差不多的问题
    wdwwtzy
        2
    wdwwtzy  
       Sep 19, 2022
    如果你问的是这个问题的话,那不是很简单
    假如你*是成对出现的话,用* split 之后,type=2 永远会在奇数索引出现。

    但是我猜你想问的不是这个问题。
    huangzhe8263
        3
    huangzhe8263  
       Sep 19, 2022
    不不不,看看 LZ 的发帖记录,问的就是这个问题。

    建议还是先去学一下基本的知识再来问吧。
    bytesfold
        4
    bytesfold  
       Sep 19, 2022
    from pprint import pprint
    data = r"两个人的小森林有*2*个热点*爆*词你还未看(217054)"
    pprint([{'type': 1 if len(i) != 1 else 2, 'text': i} for i in data.split("*")])
    bytesfold
        5
    bytesfold  
       Sep 19, 2022
    打扰了,PHP..
    laoyur
        6
    laoyur  
       Sep 19, 2022
    regex 找出被星星夹着的部分的索引,然后所有分组都能抽取出来了

    话说第一眼扫过你的原文,还以为是被和谐过的语句呢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2466 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 02:13 · PVG 10:13 · LAX 19:13 · JFK 22:13
    ♥ Do have faith in what you're doing.