1

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?

4
  • 1
    Why use $s="|"? Please post the line example. Maybe you need preg_replace('/\b(' . $id . '\b.*)(\R)/', '$1 ' . $text . '$2', $data_update, 1);? See this PHP demo. Commented May 3, 2020 at 21:46
  • @WiktorStribiżew I need to patch for EOL because the end of line has been inserted in the flat file text as PHP_EOL so you can think of my data variable as this: $data_update = "23423 in between some text".PHP_EOL; $data_update .= "00000 in between some more text".PHP_EOL; $data_update .= "11111 in between even more text".PHP_EOL; Commented May 3, 2020 at 23:49
  • If you need help, provide an MCVE (minimal complete verifiable example). Commented May 4, 2020 at 0:24
  • your example helped and that PHP demo was great for me to figure it out! thank you! @WiktorStribiżew Commented May 4, 2020 at 1:46

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.