skip to Main Content

Assume data.php has three variables like below:

$first = 1;
$second = 1;
$third = 1;

My question is how to get the 1 from $second and change it to 3? So it becomes:

$first = 1;
$second = 3;
$third = 1;

I’m trying to do this from another file, let’s say index.php. I have refer to the below answer but I don’t know what should I put in the find of the method below? ( The below code is from index.php )

file_put_contents ( $file, str_replace( 'find', 3, file_get_contents ( $file ) ) );

( https://stackoverflow.com/a/3575012/20454874 )

str_replace('$second = 1;', '$second = 3') only works for the first time. Because the value to search for is different already after the first time.

The reason behind it is that I have an HTML input and I want to save the value into the file data.php, that’s why the find ( the first parameter search ) is dynamic.

2

Answers


  1. Use regex to find dynamic content:

    $newContent = preg_replace('/$second = d+;/', '$second = ' . $newValue . ';', $content);
    
    Login or Signup to reply.
  2. Ok, so what I gathered from comments I think I know the solution to your problem:

    You are trying to find values in the document, but I think you should be focussing on the key and use regex to extract the value with preg replace like so:

    $content = '$first = 1;
    $second = 3;
    $third = 1;';
    
    $pattern = '/($first = )(d+);/m';
    
    $replacement = '$1 your_new_value_here';
    $replaced = preg_replace($pattern, $replacement, $content);
    var_dump($replaced);
    

    $pattern is a regex looking for, in this case the $first = section with any number behind it
    $replacement contains $1, which is the first section of the regex(being literally $first = , and the second part is w/e you want to put in as a number

    Then I use preg_replace to do the replacement for me. You can search for any key this way, and replace it’s value.

    PS: Please look at the links provided, the regex one is customized for this use-case.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search