5

Let's assume that $body is equal to

something 
that 
does 
not 
interest 
me 
<!-- start -->
some
html
code
<!-- end -->
something
that
does
not
interest
me

If I use

$body=preg_replace("(.*)<!-- start -->(.*)<!-- end -->(.*)","$2",$body);

I obtain:

Warning: preg_replace() [function.preg-replace]: Unknown modifier '<'

How have I to correct?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tic
  • 4,009
  • 15
  • 45
  • 86
  • 3
    It probably would be easier to get the position of *start* and the position of *end* with `strpos` and then get just the part between these positions with `substr`. – Gumbo Mar 26 '10 at 17:48
  • 1
    Possible duplicate of *[Warning: preg\_replace(): Unknown modifier '\]'](https://stackoverflow.com/questions/20705399/warning-preg-replace-unknown-modifier)* (same reason, missing regular expression delimiters) – Peter Mortensen Jul 04 '19 at 10:49

2 Answers2

16

A preg pattern needs a pair of characters which delimit the pattern itself. Here your pattern is enclosed in the first pair of parentheses and everything else is outside.

Try this:

$body=preg_replace("/(.*)<!-- start -->(.*)<!-- end -->(.*)/","$2",$body);

This is just about the syntax, and there is no guarantee on the pattern itself which looks suspicious.

Assuming the text in your example:

preg_match('#<!-- start -->(.*?)<!-- end -->#s', $text, $match);
$inner_text = trim($match[1]);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matteo Riva
  • 24,728
  • 12
  • 72
  • 104
  • replacing " " with "$2" solves the issue. Still I have a question, using $2 will it affect any other area? – Vinith Feb 11 '14 at 13:58
2

Try this:

$body = preg_replace("/(.*)<!-- start -->(.*)<!-- end -->(.*)/","$2",$body);
Sarfraz
  • 377,238
  • 77
  • 533
  • 578