Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php regex split string by [%%%]

Tags:

regex

php

Hi I need a preg_split regex that will split a string at substrings in square brackets.

This example input:

$string = 'I have a string containing [substrings] in [brackets].';

should provide this array output:

[0]= 'I have a string containing '
[1]= '[substrings]'
[2]= ' in '
[3]= '[brackets]'
[4]= '.'
like image 987
Rob Avatar asked Feb 22 '26 03:02

Rob


1 Answers

After reading your revised question:

This might be what you want:

$string = 'I have a string containing [substrings] in [brackets].';
preg_split('/(\[.*?\])/', $string, null, PREG_SPLIT_DELIM_CAPTURE);

You should get:

Array
(
    [0] => I have a string containing 
    [1] => [substrings]
    [2] =>  in 
    [3] => [brackets]
    [4] => .
)

Original answer:

preg_split('/%+/i', 'ot limited to 3 %%% so it can be %%%% or % or %%%%%, etc Tha');

You should get:

Array
(
    [0] => ot limited to 3 
    [1] =>  so it can be 
    [2] =>  or 
    [3] =>  or 
    [4] => , etc Tha
)

Or if you want a mimimum of 3 then try:

preg_split('/%%%+/i', 'Not limited to 3 %%% so it can be %%%% or % or %%%%%, etc Tha');

Have a go at http://regex.larsolavtorvik.com/

like image 84
Petah Avatar answered Feb 24 '26 16:02

Petah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!