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

1
  • 2
    preg_replace is the way to go, but nowhere in your example is the string POST1. That might be your problem right there. Commented Dec 3, 2019 at 15:08

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@eagers glad it helps you somehow :)
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

3 Comments

Note strtr and str_replace slightly differ in the way they substitute. See: stackoverflow.com/questions/8177296/…
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!

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.