Assign function to variable?

Asked

Viewed 346 times

2

What is the correct way to 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
?>

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

Because it doesn’t make a mistake, it just doesn’t work as expected.

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

  • Check this out echo where it should be return. I don’t quite understand the purpose of the question. It’s just a replace in the file name?

2 answers

2


I am not sure if this is what you are 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
  • 1

    Vlw man was just that...

2

I did some cleaning, removing unnecessary things.

What you need is just to use the return instead of echo, within the function.
Refer to the manual: http://php.net/manual/en/functions.returning-values.php

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

The preg_replace() I didn’t need it either. I switched to str_replace().

  • Vlw man was just that...

  • See, I got a question, what’s the advantage of using str_replace, that could make the preg_replace unnecessary?

  • preg_replace involves a more complex execution. That’s it. To replace an exact value, something simpler like str_replace.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.