Home » Php » php – How to use a function inside string?

php – How to use a function inside string?

Posted by: admin July 12, 2020 Leave a comment

Questions:
'<a rel="nofollow" href="$1" class="bbc_link new_win" target="_blank">'

I would like use the urlencode() function:

 '<a rel="nofollow" href="urlencode($1)" class="bbc_link new_win" target="_blank">'

… but I can’t use this:

 '<a rel="nofollow" href="'.urlencode($1).'" class="bbc_link new_win" target="_blank">'

… because $1 is not a variable in the string; it is instead a meta-variable in a simple free forum.

it send http://www.test.com/out.php?out=http://www.example.com

How to&Answers:

how about this crazy hack?

<?
$_ = 'urlencode';
echo "<a rel=\"nofollow\" href=\"{$_($1)}\" class=\"bbc_link new_win\" target=\"_blank\">";

Answer:

Check out this trick:

function foo() { return "title"; }

$func = function($param) { return $param; };

$link = 'http://www.test.com/out.php?out=http://www.example.com';
echo "<a rel=\"nofollow\" href=\"{$func(urlencode($link))}\" class=\"bbc_link new_win\" target=\"_blank\">{$func(foo())}</a>";

$func() will be called as a function, and the expression in the parentheses will be evaluated as any other PHP code.

hack is found here

Answer:

There is a way to do this, but take my advice and do not use it. you should not use function calls inside strings.
However I´ll post an example just to show what PHP is capable of.

BUT THIS IS AN EXTREME SAMPLE OF BAD PROGRAMMING!!!!

<?php
class FunctionAgent{
    public function __call($name,$args){
        switch (count($args)){
            case 0:
                return  $name();
                break;
            case 1:
                return  $name($args[0]);
                break;
            case 2:
                return  $name($args[0],$args[1]);
                break;  
            case 3:
                return  $name($args[0],$args[1],$args[2]);
                break;
            case 4:
                return  $name($args[0],$args[1],$args[2],$args[3]);
                break;
            case 5:
                return  $name($args[0],$args[1],$args[2],$args[3],$args[4]);
                break;
        }
    }   
}

$_ = new  FunctionAgent();
echo "the current date is {$_->date("y-m-d")}";

?>

Answer:

You can’t do this. You need to encode the value where it’s generated or where it’s replaced in this string, not in this template where you don’t have access to it.

Answer:

I’ve just reviewed the string parsing section of the PHP manual and there doesn’t appear to be a way of calling a function from within a quoted string (except for dynamically assigning a variable name). Sorry.

Answer:

You need to extend how your templating engine works in order to support this. There’s no way to make PHP do it for you.