sprintf function not evaluating
I'm trying to remove non-RFC characters after filtering a URL with other methods. This method breaks:
$query = 'www.example.com_-.su_-.1Mk8ij_-.www.cs.cmu.edu_-.~mjw_-.recipes_-.cheese_-.cheese-garlic-biscuits.html';
$query = preg_replace('/([^a-zA-Z0-9._-])/e', 'sprintf("_-%2.2x", ord($1))', $query);
The error returned is
Failed evaluating code: \开发者_运维知识库nsprintf("_-%2.2x", ord(~))
It breaks on other examples as well and I can't figure out why. Can anyone point me in the right direction?
Because the $1
is getting filled in already due to variable interpolation, and thus you're trying to call ord(~)
instead of ord("~")
. Use "$1"
instead of $1
.
$query = preg_replace('/([^a-zA-Z0-9._-])/e', 'sprintf("_-%2.2x", ord("$1"))', $query);
The clue is ord(~)
. A literal passed to ord
should be quoted.
It should be 'sprintf("_-%2.2x", ord("$1"))'
, notice the double quotes around $1
.
精彩评论