0

I want to replace the first occurence of a line in a file. So for example I want to find '@base' in a file and replace it with '@base:20;'. I found this one: how to replace a particular line in a text file using php?, however this replaces all the occurences of the string that is found, and I only want the first one.

Anyone got an idea?

My file looks like this:

@base: 24px;
@border-color: #B2B;

.underline { border-bottom: 1px solid green }

#header {
  color: black;
  border: 1px solid @border-color + #222222;

  .navigation {
    font-size: @base / 2;
    a {
    .underline;
    }
  }
  .logo {
    width: 300px;
    :hover { text-decoration: none }
  }
}

I want to replace the whole line where the first occurence of @base is in. I want to replace it with '@base: 50px;'. So the output would be like this:

@base: 50px;
@border-color: #B2B;

.underline { border-bottom: 1px solid green }

#header {
  color: black;
  border: 1px solid @border-color + #222222;

  .navigation {
    font-size: @base / 2;
    a {
    .underline;
    }
  }
  .logo {
    width: 300px;
    :hover { text-decoration: none }
  }
}

The pixels after @base can be different so that's why I can't find the whole line and replace that.

Community
  • 1
  • 1

2 Answers2

0

You could try something like this.

$content = file("yourfilepath");
for($i = 0; $i < count($content); $i++) {
    if (strpos($content[$i], "@base") !== false) {
        $content[$i] = "@base:20;\n"
        break;
    }
}
file_put_contents(implode(PHP_EOL, $content));

I hope that will work.

M4R1KU
  • 710
  • 7
  • 22
0

You can accomplish this with the help of preg_match and preg_replace.

Start by reading the file into an array, traverse the array and locate the line that matches what you need to replace.
Then modify the line and break the loop so only the first occurrence is changed.
Finally, write the lines back to the file.

<?php

$lines = file('file.css');

// note that $line is used as a reference
// so we can modify the existing array

foreach ($lines as &$line){

    $isMatch = preg_match('#base:\s(\d+)px;#',$line);

    if ($isMatch){

        $line = preg_replace('#\d+#','50',$line);
        break;

    }

}

file_put_contents('file.css',implode('',$lines));

preg_match will test each line until the pattern is found.
We are looking for a line that has the string base: [digits]px;.

If a match is found we modify the line using preg_replace replacing the pattern of [digits] with the value 50 and break the loop so no further changes are done.

Finally, we implode the modified array into a string using nothing as a delimiter and write the contents back to the file.

Alex Andrei
  • 7,315
  • 3
  • 28
  • 42