Assign function to variable?

3

How to properly perform the following assignment:

preg-replace.php

<?php
function file_name(){
    $pg = $_SERVER["PHP_SELF"];
    echo  $path_parts = pathinfo($pg, PATHINFO_FILENAME);//preg-replace
}
$string = file_name();//<<<---- como fazer isso corretamente
$string_f = preg_replace('/-/',' ',$string);
echo $string_f;//preg replace <<---resultado esperado
?>

Because the result is preg-replace and not preg replace .

Why do not you give an error, it just does not work as expected.

My question is how to assign the result of the file_name() function (the "preg-replace" string) to a variable and then use that variable ...

    
asked by anonymous 12.07.2017 / 07:37

2 answers

3

I'm not sure if this is what you're looking for but I need a little more detail to get a more detailed answer.

 function file_name(){
    $pg = $_SERVER["PHP_SELF"];
    return pathinfo($pg, PATHINFO_FILENAME);//tem de colocar return
}
$string = file_name();//<<<---- como fazer isso corretamente
$string_f = preg_replace('/-/',' ',$string);
echo $string_f;//preg replace <<---resultado esperado
    
12.07.2017 / 10:05
2

I did a cleaning, removing unnecessary things.

What you need is to only use return instead of echo , within the function.
See the manual: link

<?php
function file_name() {
    return pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);
}
$str = str_replace('-', ' ', file_name());
echo $str;

The preg_replace () also had no need. I switched to str_replace () .

    
12.07.2017 / 10:31