2

Is there a way to automatically replace an echoed word or phrase in PHP with something predfined? I tried using define(), but that isn't working the way I'd like (or maybe I'm not doing it correctly.

In my database I have all US states but their names are abbreviated as such; MO, AK, AL, IL...

What I'd like to do is create a file that defines MO as Missouri, and IL as Illinois and when MO is echoed, it is automatically replaced with Missouri.

Is there a good way to do this?

LIGHT
  • 5,604
  • 10
  • 35
  • 78
Budove
  • 403
  • 2
  • 8
  • 19

3 Answers3

6

The best way is to buffer the output and then deal with that.

Output buffering is done by calling ob_start() before what you want is about to be echoed. You can then get everything that was echoed using ob_get_clean(), and this takes it out of the buffer queue. You can then do any kind of processing you want on it, and echo it again.

A quick example:

<?php
function echoState() { echo "NY"; }

ob_start();
echoState();
$output = ob_get_clean();
echo str_replace("NY","New York",$output);
?>

Run it, you will get New York printed on the page.

Sébastien Renauld
  • 19,203
  • 2
  • 46
  • 66
  • 1
    `ob_get_clean();` this is the key to write out a object modified later with `str_replace`. I never remember that and im here because i googled for it. Thank you. This technique is widely used to modify the Copyright year on static templates with a default value. – m3nda May 26 '15 at 13:48
3

There are several good ways. One is to create a variable that contains your text and then operate on that, rather than echoing the string right away.

Another is to use output buffering, which takes everything you echo and saves it up, allowing you to build your page and then either display it all at once, or dump it into a variable for processing.

Community
  • 1
  • 1
octern
  • 4,825
  • 21
  • 38
2

user str_replace(find,repalce,from); function to replace anything in PHP.

Use the below, if you want to replace multiple-pre assigned values:

function replacer($searchArray,$replaceArray, $text){

        $searchArray = array("illinois","NewYork","LosAngeles");    
        $replaceArray = array("IL","NY","LA");  

        return str_replace($searchArray, $replaceArray, $text);
        }

Now, the replacing part:

$text = "this is a full text containing everything you want to be replaced";

echo replacer(@$searchArray, @$replaceArray, $text);

samayo
  • 16,163
  • 12
  • 91
  • 106