PHP Dynamic Regexp replacement - php

I would like to know if there is a way to bind PHP function inside a regexp.
Example:
$path_str = '/basket.php?nocache={rand(0,10000)}';
$pattern = ? // something i have no idea
$replacement = ? // something i have no idea
$path = preg_replace($pattern, $replacement, $path_str);
Then :
echo "'$path'";
would produce something like
'/basket.php?nocache=123'
A expression not limited to the 'rand' function would be even more appreciated.
Thanks

You could do the following. Strip out the stuff in between the {} and then run an eval on it and set it to a variable. Then use the new variable. Ex:
$str = "/basket.php?nocache={rand(0,10000)}";
$thing = "rand(0,10000)";
eval("\$test = $thing;");
echo $test;
$thing would be what's in the {} which a simple substr can give you. $test the becomes the value of executing $thing. When you echo test, you get a random number.

Don't, whatever you do, store PHP logic in a string. You'll end up having to use eval(), and if your server doesn't shoot you for it, your colleagues will.
Anywhoo, down to business.
Your case is rather simple, where you need to append a value to the end of a string. Something like this would be sufficient
$stored = '/basket.php?nocache=';
$path = $stored . rand(0,10000);
If, however, you need to place a value somewhere in the middle of a string, or possibly in a variable location, you could have a look at sprintf()
$stored = '/basket.php?nocache=%d&foo=bar';
$path = sprintf($stored, rand(0,10000));

I would not try to store functions in a database. Rather store some kind of field that represents the type of function to use for each particular case.
Then inside your crontab you can do something like:
switch ($function)
{
case 'rand':
$path_str = '/basket.php?nocache='. rand(0,10000);
}
e.t.c

Related

Cut some word from php available?

Cut some word from php available ?
First access to page for example
www.mysite.com/test.php?ABD_07,_oU_876.00/8999&message=success
From my php code, i will get $curreny_link_redirect = test.php?ABD_07,_oU_876.00/8999&message=success
And i want to get $curreny_link_redirect_new = test.php?ABD_07,_oU_876.00/8999
( Cut &message=success )
How can i do ?
<?PHP
$current_link = "$_SERVER[REQUEST_URI]";
$curreny_link_redirect = substr($current_link,1);
$curreny_link_redirect_new = str_replace('', '&message=success', $curreny_link_redirect);
echo $curreny_link_redirect_new;
?>
Your str_replace call is inverse of what it should be. What you want to replace should be the first parameter, not the second.
//Wrong
$curreny_link_redirect_new = str_replace('', '&message=success', $curreny_link_redirect);
//Right
$curreny_link_redirect_new = str_replace('&message=success','', $curreny_link_redirect);
While simple way to do this is to use regex (or even static with str_replace()), I recommend to use built-in functions for url handling. This may be useful when working with complex parameters or multiple parameters:
$data = 'www.mysite.com/test.php?ABD_07,_oU_876.00/8999&message=success';
$url = parse_url($data);
parse_str($url['query'], $url['query']);
//now, do something with parameters:
unset($url['query']['message']);
$url['query'] = http_build_query($url['query']);
$url = http_build_url($url);
-please, note, that http_build_url() is a PECL function (pecl_http to be precise). The way above may look more complex, but it has benefits - first, as I've already mentioned, this will be easy to modify for working with complex parameters or multiple parameters. Second, it will produce valid url - i.e. encode such things as slashes, spaces, e t.c. - in result. Thus, result will always be correct url.
Do like this
<?php
$str = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo $str = array_shift(explode('&',$str));
Try this:
$current_link_path = substr($_SERVER['PHP_SELF'], 1);
$params = $_GET;
if ($params['message'] == 'success') {
unset($params['message']);
}
$current_link_redirect = $current_link_path . '?' . http_build_query($params);
Maybe not an answer, but a disclaimer for future visitors:
1) I would strongly recommend the function: http://pl1.php.net/parse_url.
And in that case:
$current_link = "$_SERVER[REQUEST_URI]";
$arguments = explode('&', parse_url($current_link, PHP_URL_QUERY));
print_r($arguments);
2) To build new url, use http://pl1.php.net/manual/en/function.http-build-url.php. This is the best, future modifications ready solution I think.
In that case this solution is a little overkill, but these functions are really great, and worth to introduce here.
Best regards

PHP Function and variables stored in a string in a database

I need to store data within a database, when I get the data from the database I need functions and variables in the string to be worked out as such.
Example
$str = "<p>Dear {$this->name},</p>"
I then store this in the database, and when I retrieve the string and run it through
eval("\$detail= \"$detail\";");
then the variable gets populated with the name. This is exactly what I needed and works fine.
The problem is I want to run a function with this variable as the parameter.
example. I would like to ucwords the variable.
I have tried:
$str = "<p>Dear {ucwords($this->name)},</p>" //just echoed {ucword(->name)},
$str = "<p>Dear {ucwords($this->name)},</p>" //Fatal error: Function name must be a string,
Am I going in the right direction?
Is this at all possible?
You don't need to keep PHP code in database. This is a bad practice and also can lead to security vulnerabilities.
Instead store in database string like this:
<p>Dear [name],</p>
And when you retrieve it you can just do:
$stringFromDb = str_replace("[name]", $this->name, $stringFromDb);
or
$stringFromDb = str_replace("[name]", ucwords($this->name), $stringFromDb);
Other common approach is to use sprintf. So you need to store in database string with %s as placeholders for values.
Example:
<p>Dear %s,</p>
and replace with
$stringFromDb = sprintf($stringFromDb, ucwords($this->name));
What you seem to be looking for is a simple templating language.
It's been a long while since I've written PHP (and I suddenly remember why...), but here's something I whipped up.
It should support both objects ($a->name) and arrays ($a["name"]) as input objects.
You can add new filters (name -> function name mapping) in $valid_filters.
$valid_filters = array("title" => "ucfirst", "upper" => "strtoupper");
function _apply_template_helper($match) {
global $_apply_template_data, $valid_filters;
$var = $match[1];
$filter = $valid_filters[trim($match[2], ':')];
$value = is_array($_apply_template_data) ? $_apply_template_data[$var] : $_apply_template_data->$var;
if($filter && !empty($value)) $value = call_user_func($filter, $value);
return !empty($value) ? $value : $match[0];
}
function apply_template($template, $data) {
global $_apply_template_data;
$_apply_template_data = $data;
$result = preg_replace_callback('/\{\{(.+?)(:.+?)?\}\}/', "_apply_template_helper", $template);
$_apply_template_data = null;
return $result;
}
How to use it:
$template = "Hello {{name:title}}, you have been selected to win {{amount}}, {{salutation:upper}}";
echo apply_template($template, array("name"=>"john", "amount" => '$500,000', "salutation" => "congratulations"));
The result:
Hello John, you have been selected to win $500,000, CONGRATULATIONS
I have found the following works,
If i contain the function within the class itself then it can be called using the following code
<p>Dear {\$this->properCase(\$this->rl_account->name)},</p>
But i would like to be able to do this now without having the database have the code as Alex Amiryan mentions earlier.

identify and execute php code on a string

I would like to know if it's possible to execute the php code in a string. I mean if I have:
$string = If i say <?php echo 'lala';?> I wanna get "<?php echo 'dada'; ?>";
Does anybody knows how?
[EDIT] It looks like nobody understood. I wanna save a string like
$string = If i say <?php count(array('lala'));?>
in a database and then render it. I can do it using
function render_php($string){
ob_start();
eval('?>' . $string);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
The problem is that I does not reconize php code into "" (quotes) like
I say "<?php echo 'dada'; ?>"
$string = ($test === TRUE) ? 'lala' : 'falala';
There are lots of ways to do what it looks like you're trying to do (if I'm reading what you wrote correctly). The above is a ternary. If the condition evaluates to true then $string will be set to 'lala' else set to 'falala'.
If you're literally asking what you wrote, then use the eval() function. It takes a passed string and executes it as if it were php code. Don't include the <?php ?> tags.
function dropAllTables() {
// drop all tables in db
}
$string = 'dropAllTables();';
eval($string); // will execute the dropAllTables() function
[edit]
You can use the following regular expression to find all the php code:
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
$php_code will be an array where $php_code[0] will return an array of all the matches with the code + <?php ?> tags. $php_code[2] will be an array with just the code to execute.
So,
$string = "array has <?php count(array('lala')); ?> 1 member <?php count(array('falala')); ?>";
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
echo $php_code[0][0][0]; // <?php count(array('lala')); ?>
echo $php_code[2][0][0]; // count(array('lala'));
This should be helpful for what you want to do.
Looks like you are trying to concatenate. Use the concatenation operator "."
$string = "if i say " . $lala . " I wanna get " . $dada;
or
$string = "if i say {$lala} I wanna get {$dada}.";
That is what I get since your string looks to be a php variable.
EDIT:
<?php ?> is used when you want to tell the PHP interpreter that the code in those brackets should be interpreted as PHP. When working within those PHP brackets you do not need to include them again. So as you would just do this:
// You create a string:
$myString = "This is my string.";
// You decide you want to add something to it.
$myString .= getMyNameFunction(); // not $myString .= <?php getMyNameFunction() ?>;
The string is created, then the results of getMyNameFunction() are appended to it. Now if you declared the $myString variable at the top of your page, and wanted to use it later you would do this:
<span id="myString"><?php echo $myString; ?></span>
This would tell the interpreter to add the contents of the $myString variable between the tags.
Use token_get_all() on the string, then look for a T_OPEN_TAG token, start copying from there, look for a T_CLOSE_TAG token and stop there. The string between the token next to T_OPEN_TAG and until the token right before T_CLOSE_TAG is your PHP code.
This is fast and cannot fail, since it uses PHP's tokenizer to parse the string. You will always find the bits of PHP code inside the string, even if the string contains comments or other strings which might contain ?> or any other related substrings that will confuse regular expressions or a hand-written, slow, pure PHP parser.
I would consider not storing your PHP code blocks in a database and evaluating them using eval. There is usually a better solution. Read about Design Pattern, OOP, Polymorphism.
You could use the eval() function.

How do i remove a chunk of text from a variable? (PHP)

I need to be able to remove a URL from a variable, I'm wondering how i do this.
Example - Say my script returns http://www.example.com/file.php?id=1234 i need to be able to remove the http://www.example.com/file.php?id= bit, just leaving the id number. If anyone can help, it would be great :)
Something like this?
$var = 'http://www.example.com/file.php?id=1234';
$query = parse_url($var, PHP_URL_QUERY);
$query_components = parse_str($query);
$id = $query_components['id'];
You can use regular expressions:
preg_match("/id=(\\d+)/", $url, $matches);
$id = $matches[1];
Just use $id = $_GET['id'];.
See the docs.
And don't forget to validate and sanitize.
The "id" in this case is being sent to your script as a GET variable, therefore you would access it as follows:
$id = $_GET['id'];
If you mean to say that this URL is not yours to control, then you would do this instead:
print_r(parse_url($url)); // Then analyze the output.

PHP keep me from eval ;) Variables inside string

For reasons I'd rather not get into right now, I have a string like so:
<div>$title</div>
that gets stored in a database using mysql_real_escape_string.
During normal script execution, that string gets parsed and stored in a variable $string and then gets sent to a function($string).
In this function, I am trying to:
function test($string){
$title = 'please print';
echo $string;
}
//I want the outcome to be <div>please print</div>
This seems like the silliest thing, but for the life of me, I cannot get it to "interpret" the variables.
I've also tried,
echo html_entity_decode($string);
echo bin2hex(html_entity_decode($string)); //Just to see what php was actually seeing I thought maybe the $ had a slash on it or something.
I decided to post on here when my mind kept drifting to using EVAL().
This is just pseudocode, of course. What is the best way to approach this?
Your example is a bit abstract. But it seems like you could do pretty much what the template engines do for these case:
function test($string){
$title = 'please print';
$vars = get_defined_vars();
$string = preg_replace('/[$](\w{3,20})/e', '$vars["$1"]', $string);
echo $string;
}
Now actually, /e is pretty much the same as using eval. But at least this only replaces actual variable names. Could be made a bit more sophisticated still.
I don't think there is a way to get that to work. You are trying something like this:
$var = "cute text";
echo 'this is $var';
The single quotes are preventing the interpreter from looking for variables in the string. And it is the same, when you echo a string variable.
The solution will be a simple str_replace.
echo str_replace('$title', $title, $string);
But in this case I really suggest Template variables that are unique in your text.
You just don't do that, a variable is a living thing, it's against its nature to store it like that, flat and dead in a string in the database.
If you want to replace some parts of a string with the content of a variable, use sprintf().
Example
$stringFromTheDb = '<div>%s is not %s</div>';
Then use it with:
$finalString = sprintf($stringFromTheDb, 'this', 'that');
echo $finalString;
will result in:
<div>this is not that</div>
If you know that the variable inside the div is $title, you can str_replace it.
function test($string){
$title = 'please print';
echo str_replace('$title', $title, $string);
}
If you don't know the variables in the string, you can use a regex to get them (I used the regex from the PHP manual).
function test($string){
$title = 'please print';
$vars = '/(?<=\$)[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/';
preg_match_all($vars, $string, $replace);
foreach($replace[0] as $r){
$string = str_replace('$'.$r, $$r, $string);
}
echo $string;
}

Categories