How to create a regex to remove lines with #?

Asked

Viewed 369 times

1

I’m starting with regex now so I’m not very good yet with expressions, assuming I have the following variable:

$foo = "
        #01 = linha comentada; 
        02 = valor para ser interpretado; 
        #03 = outra linha comentada;
       ";

How to create a regex to remove lines 01 and 03 leaving only line 02 to be interpreted in the future? Note: Each line ends on ;

1 answer

2


Suggestion:

<?php
$foo = "
    #01 = linha comentada; 
    02 = valor para ser interpretado; 
    #03 = outra linha comentada;
";
$limpa = preg_replace('/[\s\t]*#\d+[^;]+;/im', '', $foo);
echo $limpa;

?>

The idea of regex is:

  • [\s\t]* spaces or tabs, zero or more
  • # the character #
  • \d+ one digit, once or more times
  • [^;]+ any character excluding ; once or more
  • ; the character ;

Example: https://ideone.com/YssIgR

  • Thanks for posting the regex explained, the same works with JS?

  • 1

    @Leoletto is basically the same, uses the flag g: https://jsfiddle.net/yq0vvwcj/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.