Search code examples
phppreg-replacecarriage-returnlinefeed

How to preg_replace from indentifier to end of text with CR(LF) characters


I'm trying to split a piece of text (actually html) into two pieces, a top and bottom part. An 'identifier' (<--#SPLIT#-->) in the text marks the position to split.

To get the upper part I have the following preg_replace that does work:

$upper = preg_replace('/<--#SPLIT#-->(\s*.*)*/', '', $text); 

This leaves me with all the text that comes before '<--#SPLIT#-->'.

To get the lower part I came up with the following preg_replace that does NOT work correctly:

$lower = preg_replace('/(\s*.*)*<--#SPLIT#-->/', '', $text);

This returns an empty string.

How can I fix the second one?


Solution

  • It is better to use:

    explode('<--#SPLIT#-->', $text);
    

    Example code:

    $text = 'Foo bar<--#SPLIT#-->Baz fez';
    $temp = explode('<--#SPLIT#-->', $text);
    $upper = $temp[0];
    $lower = (count($temp > 1) ? $temp[1] : '');
    
    // $upper == 'Foo bar'
    // $lower == 'Baz fez'