Search code examples
phpregexpreg-replaceregex-groupbackreference

stuck on a simple preg_replace with backreference


Sorry guys, I got stuck on this:

$data_update = preg_replace($id.'(.*?)'.$s.PHP_EOL, $id.$1.$s.$text.PHP_EOL, $data_update, 1);

$id = '23423';
$s = '|';
$text = 'content to insert';

Basically what I am trying to do is match everything that's between $id and a PHP End of Line in a flat file text that has multiple lines and replace it with the same line that has some content inserted right before the end of line. And I have the "1" modifier at the end because I want this to happen ONLY on the line that matches that id.

What am I doing wrong?


Solution

  • I suggest using

    preg_replace('/\b(' . $id . '\b.*)(\R)/', '$1 ' . $text . '$2', $data_update, 1);
    

    The pattern will look like \b(23423\b.*)(\R) and will match

    • \b - a word boundary
    • (23423\b.*) - Group 1: the ID as a whole word and then the rest of the line
    • (\R) - Group 2: any line break sequence

    See full PHP demo:

    $id = '23423';
    $s = '|';
    $text = 'content to insert';
    $data_update = "Some text 23423 in between end\nsome text";
    $data_update = preg_replace('/\b(' . $id . '\b.*)(\R)/', '$1 ' . $text . '$2', $data_update, 1);
    

    Output:

    Some text 23423 in between end content to insert
    some text