Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regular expression to match lines starting with a special character

Tags:

regex

php

I have a text file with some configuration value. There a comment starts with a # I am trying to find a regular expression pattern that will find out all the lines that start with a #

So, sample file:

1st line
#test line this 
line #new line
aaaa #aaaa
bbbbbbbbbbb#
cccccccccccc
#ddddddddd

I want to find

#test line this 
#ddddddddd

because only these two lines start with # I tried the following code:

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

But it always outputs empty array. Anyone can help?

like image 992
Enn Fenn Avatar asked Aug 03 '13 16:08

Enn Fenn


People also ask

What is the regex for special characters?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ).

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

Which special character is used to checking beginning of line in regular expression?

These are called anchor characters: If a caret ( ^ ) is at the beginning of the entire regular expression, it matches the beginning of a line. If a dollar sign ( $ ) is at the end of the entire regular expression, it matches the end of a line.


1 Answers

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
like image 86
Tim Pietzcker Avatar answered Oct 19 '22 01:10

Tim Pietzcker