PHP regular expression to match lines starting with a special character

You forgot the multiline modifier (and you should not use the singleline modifier; also the case-insensitive modifier is unnecessary as well as the ungreedy modifier):

preg_match_all("/^#(.*)$/m",$text,$m);

Explanation:

  • /m allows the ^ and $ to match at the start/end of lines, not just the entire string (which you need here)
  • /s allows the dot to match newlines (which you don’t want here)
  • /i turns on case-insensitive matching (which you don’t need here)
  • /U turns on ungreedy matching (which doesn’t make a difference here because of the anchors)

A PHP code demo:

$text = "1st line\n#test line this \nline #new line\naaaa #aaaa\nbbbbbbbbbbb#\ncccccccccccc\n#ddddddddd"; 
preg_match_all("/^#(.*)$/m",$text,$m);
print_r($m[0]);

Results:

[0] => #test line this 
[1] => #ddddddddd

Leave a Comment