preg_replace with file_get_contents - php

I have looked at a couple of questions here, and done a Google search but I cannot seem to find the correct way to go about doing this.
I am using this function
function replace_c($content){
global $db;
$replacements = $db->query("SELECT * FROM `replacements`");
while($replace = $replacements->fetch_assoc()){
preg_replace("/".$replace['triggers']."/i",$replace['php'], $content);
}
return $content;
}
and this is my call to the function
$contents = replace_c(file_get_contents("templates/" . $settings['theme'] . "/header.html"));
It doesn't give an error, it just doesn't replace the text like it should so I am not sure if the function is actually working. I did try preg_replace_callback but I don't think I fully understand how it works and was producing nothing but errors, do I have to go the callback route, or am I just missing something in my current function?

Kira,
The preg_Replace function returns the replaced string. The $content subject you post to it will not update as a reference. So try changing the code to;
$content = preg_replace("/".$replace['triggers']."/i",$replace['php'], $content);

You never assign the return value of preg_replace to $content.... What you need is this:
$content = preg_replace("/".$replace['triggers']."/i",$replace['php'], $content);

You need to store the replaced content back to a variable.
$content = preg_replace(...);
Also, are you sure that an str_replace() wouldn't be enough?

Related

Getting invalid argument passed error when trying to preg_replace $1 variable

This is the code Im getting the error on:
$show_nav = preg_replace('#\{\$SUBMENU([0-9]+)\}#',implode("\n",$sub_menu['submenu$1']),$show_nav);
So basically I want to replace a string within the $show_nav variable such as {$SUBMENU2} with data from the sub menu array. I tested and it works just fine if I manually put in the number like so:
$show_nav = preg_replace('#\{\$SUBMENU([0-9]+)\}#',implode("\n",$sub_menu['submenu2']),$show_nav);
I also verified the regex is grabbing the proper variable by doing this:
$show_nav = preg_replace('#\{\$SUBMENU([0-9]+)\}#','$1',$show_nav);
It replaces the string with what is found in the {$SUBMENU} string. So if its {$SUBMENU3} it gives me back 3, {$SUBMENU5} it gives me back 5. But I cant seem to get it to dynamically read the $1 variable. I tried adding curly brackets, still same error:
$show_nav = preg_replace('#\{\$SUBMENU([0-9]+)\}#',implode("\n",$sub_menu['submenu{$1}']),$show_nav);
or:
$show_nav = preg_replace('#\{\$SUBMENU([0-9]+)\}#',implode("\n",$sub_menu['{submenu$1}']),$show_nav);
I know Im entering it wrong, but cant figure out the proper way of doing it. Any suggestions?
****UPDATE****
Thanks for the suggestions provided by Toto and Wiktor Stribiżew this is the code that resolved my issue, thanks again!!!
$show_nav = preg_replace_callback(
'#\{\$SUBMENU([0-9]+)\}#',
function($m) use($sub_menu) {
if(isset($sub_menu['submenu' .$m[1]]))
{
return '<ul class="nav-dropdown">' .implode("\n",$sub_menu['submenu' .$m[1]]) .'</ul>';
}
},$show_nav);
preg_replace_callback is your friend:
$show_nav = preg_replace_callback(
'#\{\$SUBMENU([0-9]+)\}#',
function($m) use($sub_menu) {
return implode("\n",$sub_menu['submenu'.$m[$1]])
},
$show_nav);

Blade render from database

In my view I have this code:
{{L::getSomeContent('content')}}
This method returns content from the database. My question is, is it possible to return and render Blade straight from the database? For example, I have stored in the database:
<img src"{{asset('somepath')}}">
But when rendering this data straight from the database, it will just show like '%7%7'
I have tried Blade::compileString
I hate to suggest this, but eval would work in this case. Before you use this, you have to make sure that the content you pass to it isn't user input. And if it is you have to sanitize it (or trust the user, if the content can be changed in some kind of admin tool)
Instead of using this method you should maybe thinking of some other way to organize your content. For paths you could use a placeholder and just do a string replace before outputting.
Anyhow, be warned: eval() will execute any PHP code that's passed.
Here's a working example. Of course you put that in some kind of helper function to not clutter your view code, but I'll leave that to you.
<?php
$blade = L::getSomeContent('content');
$php = Blade::compileString($blade);
// remove php brackets because eval() doesn't like them
$php = str_replace(['<?php', '?>'], '', $php);
echo eval($php);
?>
As I already mentioned for this particular case (a path to an asset) you could use a placeholder in your content. For example:
Stored in the database
<img src"%ASSET%some/path">
And then inside a helper function and before output, just replace it with the real path:
$content = L::getSomeContent('content');
$html = str_replace('%ASSET%', asset(''), $content);
I found the answer in the comments #blablabla :
protected function blader($str, $data = array())
{
$empty_filesystem_instance = new Filesystem;
$blade = new BladeCompiler($empty_filesystem_instance, 'datatables');
$parsed_string = $blade->compileString($str);
ob_start() and extract($data, EXTR_SKIP);
try {
eval('?>' . $parsed_string);
}
catch (\Exception $e) {
ob_end_clean();
throw $e;
}
$str = ob_get_contents();
ob_end_clean();
return $str;
}
This part seems to be working fine:
Blade::compileString($yourstring);
eval('?>' . $yourstring);

How can I call $content = str_replace PHP function

Long short, I have a function that is responsible for executing specific data from my database, but the problem is I can't use that function. To be more clear:
This is the function
function ReplaceHTMLCode_Database($content){
$content = str_replace('{SELECT_CHAR}',GetPlayerSelect(),$content);
}
function GetPlayerSelect(){
$QUERY = mysqli_fetch_array(mysqli_query( ConnectiShopDb(),
"SELECT * from ".ISHOP_MYSQL_DB.".select_char where account_id=('".$_SESSION['ISHOP_SESSION_ID']."')"
));
if($QUERY['pid_id']){
return GetPlayerInfo($QUERY['pid_id'],'name').
"(".GetPlayerRaceByJob(GetPlayerInfo($QUERY['pid_id'],'job')).")";
} else {
return "{NO_CHARACTER_LABEL}";
}
}
I hope that I'm not being vague, But I tried selected="selected">{"SELECT_CHAR"}</option> in my PHP form that is supposed to be displaying this function and it's just being displayed as $SELECT_CHAR. I'm aware that this may be part of WordPress code since
I googled how to use ReplaceHTMLCode_Database and figured out it's pretty much something to do with WP, but I'm not using WordPress or any different CMS. Any help is so much appreciated!
Your function isn't returning or changing the variable. It would need to either do this:
function ReplaceHTMLCode_Database(&$content){
$content = str_replace('{SELECT_CHAR}',GetPlayerSelect(),$content);
}
This takes the variable by reference and changes it. You could then use it like so:
ReplaceHTMLCode_Database($content);
Otherwise, you could do this:
function ReplaceHTMLCode_Database($content){
return str_replace('{SELECT_CHAR}',GetPlayerSelect(),$content);
}
Which returns a new value that you could assign somewhere, like this:
$content = ReplaceHTMLCode_Database($content);
Your ReplaceHTMLCode_Database doesn't return anything. Could it be a simple
function ReplaceHTMLCode_Database($content){
return str_replace('{SELECT_CHAR}',GetPlayerSelect(),$content);
}
Please give some information about what the function should do.

PHP to text function

I am trying to create a function that would parse php code and return the result in pure text, as if it was being read in a browser. Like this one:
public function PHPToText($data, $php_text) {
//TODO code
return $text;
}
I would call the function like this, with the params that you see below:
$data = array('email' => 'test#so.com');
$string = "<?= " . '$data' . "['email']" . "?>";
$text = $this->PHPToText($data, $string);
Now echo $text should give: test#so.com
Any ideas or a function that can achieve this nicely?
Thanks!
It's a bad bad bad bad bad idea, but basically:
function PHPToText($data, $string) {
ob_start();
eval($string);
return ob_get_clean();
}
You really should reconsider this sort of design. Executing dynamically generated code is essentially NEVER a good idea.
in this case it should be done with eval()
But always remember: eval is evil!
You will need to use the eval() function http://www.php.net/eval in order to parse the tags inside your variable $string

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