Ok I know the title is a bit confusing as I can't think of a good way to explain it. There is this function which I don't have access to and it looks something like this:
<?php function myFunction() {
?> '<img src="one.jpg" />';
<?php } ?>
Ok so everytime that function is called, it echo's the img tag. But what if I want to manipulate the img tag before it echos to the screen? Is it possible?
I want to assign it to a variable first, manipulate it and then I will echo it out. Something like this:
$image_src = myFunction();
$image_src = preg_replace('/s.*"/', $image_src);
echo $image_src;
Something like this possible?
Use output buffering:
ob_start();
myFunction();
$output = ob_get_clean();
after that, $output will contain the html that was echoed inside the function.
I am new to php and the first thing I did was create a generic function to echo a line to html:
function html_line ( $string ) // echo line to browser
{
echo PHP_EOL . $string . PHP_EOL;
}
Then I made functions for simple paragraphs and images that add html tags, for example:
function html_pp ( $string ) // echo paragraph to browser
{
html_line ( '<p>' . $string . '</p>' );
}
Other functions and variables can be used to manipulate the content any way you wish before these are called:
function html_page ( $str_title, $str_content ) // simple page with title and body
{
html_line ( '<html>' );
html_line ( '<head>' );
html_line ( '<title>' . $str_title . '</title>' );
html_line ( '</head>' );
html_line ( '<body>' );
html_pp ( $str_content );
html_line ( '</body>' );
html_line ( '</html>' );
}
function html_test () // set some variables and create a test page
{
$test_title = 'PHP Test';
$test_msg = 'Hello World!';
html_page ( $test_title, $test_msg );
}
I don't know if this answers your question but it is working well for me and could be a good starting point. If you decide to separate your functions out to a different file like I did just be sure to have correct include calls and the functions will have global scope from the caller.