Search code examples
phpregexexplode

php explode between two delimiter and delimiter not lost


how to explode string between delimiter "[" but i want delimiter not lost in example i have string like this

$str = "i want to show you my youtube channel : [youtube id=12341234] and my instagram account : [instagram id=myingaccount213]

i want result like this

  [0]=>
  string(61) "i want to show you my youtube channel : [youtube id=12341234]"
  [1]=>
  string(68) "and my instagram account : [instagram id=myingaccount213]"

if i use $tes = explode("]", $content); the "]" is lost


Solution

  • Instead of splitting, you could also match the parts that you want by matching optional horizontal whitespace chars, and then capture in group 1 as least as possible chars followed by matching [...]

    For the matches get the group 1 value using $matches[1]

    \h*(.*?\[[^][]*])
    

    Regex demo | Php demo

    Example code

    $s = "i want to show you my youtube channel : [youtube id=12341234] and my instagram account : [instagram id=myingaccount213]";
    preg_match_all("~\h*(.*?\[[^][]*])~", $s, $matches);
    print_r($matches[1]);
    

    Output

    Array
    (
        [0] => i want to show you my youtube channel : [youtube id=12341234]
        [1] => and my instagram account : [instagram id=myingaccount213]
    )
    

    Another option is making the pattern a bit more specific for youtube or instagram:

    \h*(.*?\[(?:youtube|instagram)\h+id=[^][\s]+])
    

    Regex demo