Search code examples
phppreg-match

preg_match replace entire line


I am new to PHP preg_match function. How to replace everthing with nothing before specific character using preg_match?

Sample:

text1
text2
text3
text3
# text 5

I want to get rid everything before the '#' sign. is that possible? here is my code bu not sure

$replace_match = '/^.*' . '#' . '.*$(?:\r\n|\n)?/m';

Solution

  • You can match all lines that do not start with # until you can match # at the start.

    ^(?:(?!#).*\R)+#
    
    • ^ Start of string
    • (?: Non capture group
      • (?!#).*\R Negative lookahead, assert not # directly at the right. If that is the case, match the whole line followed by a newline
    • )+ Close group and repeat 1+ times to match at least a single line
    • # Match literally to make sure that the character is present

    Regex demo

    In the replacement use a #

    Example

    $re = '/^(?:(?!#).*\R)+#/m';
    $str = 'text1
    text2
    text3
    text3
    # text 5';
    
    echo preg_replace($re, "#", $str);
    

    Output

    # text 5