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 );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法