Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace displayed output with PHP

Tags:

php

mysql

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?

like image 946
Budove Avatar asked Dec 10 '25 13:12

Budove


1 Answers

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.

like image 64
Sébastien Renauld Avatar answered Dec 12 '25 03:12

Sébastien Renauld



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!