Forum Moderators: coopster
However, I am having trouble with the preg_replace.
This works:
$new_contents = preg_replace ("/$replace1(.*)<\/td>/", "cut out", $contents); Where $replace1 is the beginning part of the html I want to cut.
But, I want to specify the second part and not just use <\/td>. So I thought it would be:
$new_contents = preg_replace ("/$replace1(.*)$replace2/", "cut out", $contents); But this doesn't work. Could someone check my syntax, please? Or is it even possible to have two variables in the expression?
Many thanks in advance.
[php.net...]
first part is a pattern, then replacement, and last is a string in which the replacement takes part.
In the pattern you can put as many variables as you like, just remember it needs to be still a valid pattern.
What I would do is move the pattern outside of the preg:
$pattern = "/$replace1(.*)$replace2/";
$new_contents = preg_replace ($pattern, "cut out", $contents);
this way you can echo $pattern; and check if it is valid.
Hope this helps
Michal
Many thanks for your reply. I guess the problem is with my understanding of the pattern.
Basically I want to replace a large chunk of html from a file like this:
<html>
<head>
<title> Cutting </title>
</head><body>
from
<p>This is the chunk I want to remove</p>
here
</body>
</html>
So replace everything from "from" to "here" by doing this:
$replace1 = "from";
$replace2 = "here";
$pattern = "/$replace1(.*)$replace2/";
$new_contents = preg_replace ($pattern, "cut out", $contents); where $contents is the html file. Am I being too hopeful?
$pattern = "/(".$replace1.".+".$replace2.")/i";
Could you provide us with real example of the ending?
Michal
PS. Eelix's solution could also work, if you don't use separate $pattern, then I am not sure how will $ be parsed.
$pattern = "/(".preg_quote($replace1,'/').".+".preg_quote($replace2,'/').")/i";
It must be in my pattern. When I try this:
$contents = "
from
<p>This is the chunk I want to remove</p>
here
"; it doesn't work, but this works fine:
$contents = "
from<p>This is the chunk I want to remove</p>here
"; So this is the whole script:
<?php$replace1 = "from";
$replace2 = "here";
$contents = "
from
<p>This is the chunk I want to remove</p>
here
";
// $pattern = "/(".preg_quote($replace1,'/').".+".preg_quote($replace2,'/').")/i";
// $pattern = "/(".$replace1.".+".$replace2.")/i";
$pattern = "/$replace1(.*)$replace2/";
echo "The pattern is ".$pattern."<br><br>";
$new_contents = preg_replace ($pattern, "cut out", $contents);
echo $new_contents;
?>
Thanks again for any insight.
The 'i' actually means to ignore the case. 'm' is the modifier for 'multiline' patterns, however, I don't think it applies here.
[us.php.net...]
You may want to try a pattern like this:
$pattern = "/(".$replace1."[\r\n.]+".$replace2.")/";