开发者

How to use a function inside string?

开发者 https://www.devze.com 2023-01-31 04:31 出处:网络
\'<a re开发者_运维技巧l=\"nofollow\" href=\"$1\" class=\"bbc_link new_win\" target=\"_blank\">\'
'<a re开发者_运维技巧l="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 about this crazy hack?

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


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


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")}";

?>


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消