1

I have these variables:

$summary="The problem with field2 is field13.  The fix will be field7"
$_POST['field2']='thiscomputer';
$_POST['field7']='thishotfix';
$_POST['field13']='thisapplication';

I'm trying to craft a preg_replace() that will find /field[0-9]/ within the string and replace it with the value from the $_POST array. But I keep coming up short. Maybe preg_replace() is the wrong function to use in this instance. I'm trying to replace an old long list of 50+ str_replace's

Thanks for any help that can point me in the right direction

eagers
  • 59
  • 2
  • 8
  • 2
    preg_replace is the way to go, but nowhere in your example is the string `POST1`. That might be your problem right there. – colburton Dec 03 '19 at 15:08

2 Answers2

2

How about this single line str_replace instead of preg_replace? You may need to fix some spacing, that can be resolved by the array value

echo str_replace(array_keys($_POST),array_values($_POST),$summary);

Output:

The problem with thiscomputer is thisapplication.  The fix will be thishotfix

WORKING DEMO: https://3v4l.org/quYVO

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
1

strtr, though I'd probably want to copy and filter that post array:

<?php

$summary="The problem with field2 is field13.  The fix will be field7";
$_POST['field2']='thiscomputer';
$_POST['field7']='thishotfix';
$_POST['field13']='thisapplication';

echo strtr($summary, $_POST);

Output:

The problem with thiscomputer is thisapplication.  The fix will be thishotfix
Progrock
  • 7,373
  • 1
  • 19
  • 25
  • Note strtr and str_replace slightly differ in the way they substitute. See: https://stackoverflow.com/questions/8177296/when-to-use-strtr-vs-str-replace – Progrock Dec 03 '19 at 15:50
  • Have a look here the benchmark https://simplemachines.org/community/index.php?topic=175031.0 – A l w a y s S u n n y Dec 03 '19 at 16:04
  • This does indeed work, but since I am replacing old str_replace code, sticking with a new str_replace method works better for my team. Still Thank you! – eagers Dec 03 '19 at 16:30