Regex replace

Hello,

I’m trying to built a fully dynamic website. My client made a lot of websites with the same layout but with different content, for me the job to make it easy update-able. This means I have to adjust a part of my .htaccess file by editing it with a php script.

The problem is that I cannot find a solution for the following problem:

.htaccess has the following lines:

#O UD
Bladiebla usercontent
Bladiebla
Etc..
#C UD

The lines between the #O UD and #C UD lines should be updated. I thought I’d use the file_get_contents function, search and replace the lines with preg_replace and then save the file.

I’ve searched a lot but cannot find a working answer. What arguments do I use in the preg_replace function?

Thanks in advance,
xTaste :slight_smile:

I’m not the best with regular expressions but this seems to do the job:

Expression:

(\\#[A-Z ]+)(\\r[\\w\\s.]+)(\\#[A-Z ]+)

Matches:

[B]Match $1:[/B] #O UD

[B]Match $2:[/B]
Bladiebla usercontent
Bladiebla
Etc..

[B]Match $3:[/B] #C UD

Thank you! :slight_smile: …but I tried it and it doesn’t work :frowning: I already had something like that only with
instead of \r and with [a-zA-Z ]+

So I’m still wondering how to do this…

Just to be sure, I have done this correctly?


$content = file_get_contents('./.htaccess');
echo '<pre>';
echo preg_replace("((\\#[A-Z ]+)(\\r[\\w\\s.]+)(\\#[A-Z ]+))", "\\2", $content);
echo '</pre>';

xTaste

Look at this (it presumes you only have once occurrence of #O UD and #C UD).


<?PHP
/* the name of your file */
$file_name = "whatever.txt";

/* read the file contents into a string */
$contents = file_get_contents($file_name);
$beg_of = "#O UD";
$end_of = "#C UD";

/* remove all occurences of #O UD */
$contents = str_replace($beg_of, "", $contents);

/* remove all occurences of #O UD */
$contents = str_replace($end_of, "", $contents);

/* convert content to an array */
$lines = explode("\
", $contents);

/* remove first element as it is empty */
array_shift($lines);

/* remove last element as it is empty */
array_pop($lines);

/* create new content from the array */
$new_content = implode("\
", $lines);

/* do whatever you want with the results */
echo nl2br($new_content);
?>


Interesting approach! :slight_smile: And it will work. Only, I really would like to know how to do this with preg_replace, haven’t found a solution yet. I’ll post it if I have one. If anyone has a new idea, feel free to post it.

Solution: preg_replace(“((\#[A-Z ]+)([^\#]+)(\#[A-Z ]+))”, “$2”, $content);

I tried this before but I forgot the # needs an \ … Thanks to chris.upjohn for making me realize that! :slight_smile: