Search code examples
phpregexplaceholdertext-extractiondelimited

Get all pipe-delimited words inside of all curly braced expressions in a string


I have a string like this:

$str = "{It|This} part, but also {spin|rotation} the words";

i want to split {It|This} and {spin|rotation} to It, This ,spin,rotation by regular expression.

I need regular expression for this.

$str = "{It|This} part, but also {spin|rotation} the words";
$pattern =''; // need a pttern here
$arr = preg_split($pattern,$str);
print_r($arr);

Solution

  • Explanation :

    Using preg_match_all() the content between the { and } are matched and those matches are cycled through via a foreach , exploding the argument by | and then finally doing an implode()

    The code..

    $str = "{It|This} part, but also {spin|rotation} the words";
    preg_match_all('/{(.*?)}/', $str, $matches);
    foreach($matches[1] as $v)
    {
        $new_val[]=explode('|',$v);
    }
    echo $new_val=implode(',',call_user_func_array('array_merge',$new_val));
    

    OUTPUT :

    It,This,spin,rotation
    

    Demonstration