Re: Help with regular expressions
| From: | liljim | Date: | Fri, 25 Jan 2002 09:31:23 +0000 |
| Subject: | Re: Help with regular expressions | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-82074@lists.php.net to get a copy of this message | ||
Hi Daniel,
"José daniel ramos wey" ...
> Hi! I´m new to regular expressions, and it seems to be an art to make it
> work as expected.
>
> I´m trying to remove all "single-line" comments from an string - that´s
> everything after "//" to the end of a line. I expected that this would do
> the job: ereg_replace("//[[:alnum:]]*\n","",$string), but it didn´t work.
>
> Any tips?
First off, IMO, you're better off using pcre regex functions than the posix
ones:
http://www.php.net/preg_replace
<?
$string = "// line 1\nNormal line\n// line 2 with a few odd
characters\"£$%^&*()_\nAnother normal line.";
$string = preg_replace('!^//.*$!m', '', $string);
echo $string;
?>
Your regex is basically saying this:
//[[:alnum:]]*\n
Match anywhere in the string (you have no anchor as to where the // should
start), consume anything that is alphanumeric (0 through 9, a through z), as
many times as they occur, followed by a new line. Thus, your regex would
consume stuff like this:
//sdfffffffffffffffffffffffffffffffffdfffsdfsdfsdddddd12345678900987sdfsdbfs
but not
//
sdfffffffffffffffffffffffffffffffffdfffsdfsdfsdddddd12345678900987sdfsdbfs
or
// this is a comment.
as for my example, I'm using exclamation marks as the delimiters, the m
modifier which matches $ at the end of every newline, and ^ at the start of
every new line.
So:
!^//.*$!m
Means
^ at the start of the line
// if there are two of these
.* match everything
$ up to the end of the new line
and replace it with nothing.
Check the pattern modifiers etc in the manual.
HTH
~James