Jump to content

Newbie question on delimiters in preg_replace


wolfeblog

Recommended Posts

I have the solution to my problem; I just don't know why it works and that disturbs me.

I used to write a lot of C/ASM code; I'm rusty now. I'm totally new to PHP.

I want to remove all instances of <!--word--> from $content and add a preface string, $preface.

So, it seems

[b]$content = $preface . preg_replace("<!--word-->", "", $content); [/b]

will suffice. It doesn't.

This changes "<!--word-->" into "<>".

Messing about, I find that:

[b]$content = $preface . preg_replace("^!--word-->^", "", $content); [/b]

works fine. I believe the ^ operator is a delimiter that means 'new line'. Why adding this would fix it (since there's not a new line at that point in $content) I have no clue. Any insights/advice? And, especially, why doesn't the first version work?

Thanks very much in advance,
-wolfe
Preg replace works with Perl'esque regex so you'll want a pair of //'s around your pattern.  I believe the following regex will work as expected:

[code]
$content = $preface . preg_replace("/(<!--word-->)/", "", $content);
[/code]

As a side note, if you are only replacing the static string "<!--word-->", then str_replace will do the job more efficiently.

[code]
$content = $preface . str_replace("<!--word-->", "", $content);
[/code]

Best,

Patrick

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.