dougong2005 2019-04-04 15:41
浏览 314
已采纳

php preg_split将字符串从方括号拆分为数组

I want to split the string from square brackets without removing any character. I tried the below code but it's not working for me.

$value = "<p>&nbsp;Lorem ipsum dolor [State] sit amet, consectetur [City] adipisicing [TopJob7] elit, sed do eiusmod [JobType]</p>";

$tagsReplace = preg_split('/[\[]*[\][]/U', $value, -1);

echo '<pre>';
print_r( $tagsReplace );
exit;

When I run the above code I got the output like

Array
(
    [0] => <p>&nbsp;Lorem ipsum dolor 
    [1] => State
    [2] =>  sit amet, consectetur 
    [3] => City
    [4] =>  adipisicing 
    [5] => TopJob7
    [6] =>  elit, sed do eiusmod 
    [7] => JobType
    [8] => </p>
)

I want output like below.

Array
(
    [0] => <p>&nbsp;Lorem ipsum dolor 
    [1] => [State]
    [2] =>  sit amet, consectetur 
    [3] => [City]
    [4] =>  adipisicing 
    [5] => [TopJob7]
    [6] =>  elit, sed do eiusmod 
    [7] => [JobType]
    [8] => </p>
)

Please help me where I did a mistake.

  • 写回答

1条回答 默认 最新

  • douwen9534 2019-04-04 15:47
    关注

    Your pattern [\[]*[\][] matches 0+ times an opening bracket and then either a opening or closing bracket giving you either a [ or n ]

    To keep the delimiters you could capture in a group matching from [ to ] and match what is in between using a negated character class matching not a closing bracket.

    Use the PREG_SPLIT_DELIM_CAPTURE flag to keep the delimiter.

    Note that you don't need the /U flag.

    (\[[^]]+\])
    

    Explanation

    • ( Capturing group
      • \[ Match [
      • [^]]+ Match 1+ times not a ]
      • \] Match ]
    • ) Close group

    Regex demo | Php demo

    For example:

    $value = "<p>&nbsp;Lorem ipsum dolor [State] sit amet, consectetur [City] adipisicing [TopJob7] elit, sed do eiusmod [JobType]</p>";
    $tagsReplace = preg_split('/(\[[^]]+\])/', $value, -1, PREG_SPLIT_DELIM_CAPTURE);
    print_r( $tagsReplace );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀