How do I replace using the following code?
ereg_replace("%Data_Index\[.\]%", $this->resultGData[$key ][\\1], $var)
I want to replace the number in [] %Data_Index
to $this->resultGData[$key ][\\1] same %Data_Index
and how ex %Data_Index[1] = $this->resultGData[$key][1], $var);
replace number in %Data_Index[...........] in []
to $this->resultGData[$key ][............]
same number
Try the preg_replace() function with the e modifier instead:
preg_replace('/%Data_Index\[(\d+)\]%/e', '$this->resultGData[$key][\1]', $var);
Note that this function uses Perl-compatible regular expressions instead of POSIX-extended regular expression.
your question is a little bit hard to understand
the smartest way to replace what you are asking I believe would be using a cycle
for example if you know that $this->resultGData[$key ][] has 10 elements on them you could simply do this, asuming %Data_Index[1] (are you sure it isn't $Data_Index? i'll asume that) you can try the following
$total = count($this->resultGData[$key ]); //we get the total of elements in that key
for($i=0;$i<$total;$i++)
{
$Data_Index[$i] = $this->resultGData[$key][$i];
}
now if the $key changes, you'd need to do this for every $key :)
keep practicing your english, it's a really useful tool in the IT field :) (not that i'm very a good at it either :P)
Related
I found this neat code from: https://www.webmasterworld.com/php/3444822.htm
First example seems to work well:
$firstname = "Eric";
$lastname = "Johnsson";
echo preg_replace("/\{([^\{]{1,100}?)\}/e", "$$1", "{lastname}, {firstname}");
But when I try to use second array version, it gives me index and other errors what ever combinations I try:
$values = array('firstname'=>'Eric', 'lastname'=>'Johnsson');
echo preg_replace("/\{([^\{]{1,100}?)\}/e", "$values[$1]", "{lastname}, {firstname}");
In PHP 5.5x it "should" work. PHP 7.x -> needs to have second argument a function, not accepting -e argument on regex.
Does anyone know working solution to second version? I rather not use export function to extract variables to the working scope.
You need to use preg_replace_callback as in the code below:
$values = array('firstname'=>'Eric', 'lastname'=>'Johnsson');
echo preg_replace_callback("/{([^{}]*)}/", function($m) use ($values) {
return !empty($values[$m[1]]) ? $values[$m[1]] : $m[0];
}, "{lastname}, {firstname} {somestring}");
See the PHP demo
Note that to pass the $values to the anonymous callback function, you need to pass it within use argument. With !empty($values[$m[1]]) you can check if your array contains the necessary key-value, and if yes, replace with it, and if not, just restore the match with the current match value, $m[0].
Note you do not need to escape { and } in this pattern, and you may just use {([^{}]*)} to match any number of chars other than { and } between { and }. If you are only interested in the substrings containing word chars, a {(\w+)} pattern could be more suitable.
Please forgive me if I'm way off here but I'm trying to create a simple template parser and to do this I'm using regular expressions to find template tags and replace them with dynamic text.
I want to be able to use a closure to return the replacement text. For example:
// Example 1
$tag['\{{title:(.*)}}\'] = function($1)
{
return $1;
};
// Example 2
$tag['\{{title:(.*)}}\'] = function($1)
{
$something = ['One', 'Two', 'Three'];
return $1 . implode($something);
};
// Now do the replacements
foreach($tag as $pattern=>$replacement)
{
preg_replace($pattern, $replacement, $template);
}
I've included example 2 to explain that the result maybe dynamic and this is why I can't simply use strings.
I also feel like I need to explain why I'd need such functionality. The patterns are meant to be expandable, so other developers can add their own patterns easily.
If I've completely off the mark and this isn't going to be achievable, could you point me in the direction to achieve the same/similar functionality?
also, side note - not my main question - but is there a way to do multiple preg_replace in one go instead of looping through, seems inefficient.
I have a string like
"subscription link :%list:subscription%
unsubscription link :%list:unsubscription%
------- etc"
AND
I have an array like
$variables['list']['subscription']='example.com/sub';
$variables['list']['unsubscription']='example.com/unsub';
----------etc.
I need to replace %list:subscription% with $variables['list']['subscription'],And so on
here list is first index and subscription is the second index from $variable
.Is possible to use eval() for this? I don't have any idea to do this,please help me
Str replace should work for most cases:
foreach($variables as $key_l1 => $value_l1)
foreach($value_l1 as $key_l2 => $value_l2)
$string = str_replace('%'.$key_l1.':'.$key_l2.'%', $value_l2, $string);
Eval forks a new PHP process which is resource intensive -- so unless you've got some serious work cut out for eval it's going to slow you down.
Besides the speed issue, evals can also be exploited if the origin of the code comes from the public users.
You could write the string to a file, enclosing the string in a function definition within the file, and give the file a .php extension.
Then you include the php file in your current module and call the function which will return the array.
I would use regular expression and do it like that:
$stringWithLinks = "";
$variables = array();
// your link pattern, in this case
// the i in the end makes it case insensitive
$pattern = '/%([a-z]+):([a-z]+)%/i';
$matches = array();
// http://cz2.php.net/manual/en/function.preg-replace-callback.php
$stringWithReplacedMarkers = preg_replace_callback(
$pattern,
function($mathces) {
// important fact: $matches[0] contains the whole matched string
return $variables[$mathces[1]][$mathces[2]];
},
$stringWithLinks);
You can obviously write the pattern right inside, I simply want to make it clearer. Check PHP manual for more regular expression possibilities. The method I used is here:
http://cz2.php.net/manual/en/function.preg-replace-callback.php
I need to use PHP contants in foreach loop:
define('WEBS', 'http://google.com, http://yahoo.com');
foreach (WEBS as $a) {
//do something
}
However I managed to do that by following code, although it works fine but aptana editor shows syntax error. Please guide me how to do that in the correct manner.
foreach (get_defined_constants(true)['user']['WEBS'] as $w) {
//do something
}
You have to explode the values first
foreach (explode(', ', WEBS) as $url) { ...
explode() will break a string into an array so that you can iterate through it
Alternatively, you could even use preg_split.
foreach(preg_split('/,\s*/', WEBS) as $url) { ...
preg_split() allows you to split your string based on a regular expression. It returns an array. As an example, using this regex, the space following the comma is optional.
# a string like this
foo.com, hello.com,world.com, test.com
# would still split properly to
[
'foo.com',
'hello.com',
'world.com',
'test.com'
]
Regex methods are not always necessary. But I thought I'd show you that a little more control is available when it's necessary.
Aptana is showing you an error because you can't use [] after a func() prior to PHP 5.4. To get around that, you can do things like:
$constants = get_defined_constants(true);
$constants['user']['WEBS'];
But in this case WEBS should be just fine. The only issue you were having is that you needed to convert the string to an array first.
Looks like misuse of constants.
It seems you need a regular variable of array type.
$webs = array('http://google.com', 'http://yahoo.com');
foreach ($webs as $a) {
//do something
}
If you still thinks that constants is what you need - better ask another question, explaining why so, and be told of what you're doing wrong
I'm trying to create a simple framework in PHP which will include a file (index.bel) and render the variables within the file. For instance, the index.bel could contain the following:
<h1>{$variable_name}</h1>
How would I achieve this without using eval or demanding the users of the framework to type index.bel like this:
$index = "<h1>{$variable_name}</h1>";
In other words: Is it possible to render the content of a file without using eval? A working solution for my problem is this:
index.php:
<?php
$variable_name = 'Welcome!';
eval ('print "'.file_get_contents ("index.bel").'";');
index.bel:
<h1>{$variable_name}</h1>
I know many have recommended you to add template engine, but if you want to create your own, easiest way in your case is use str_replace:
$index = file_get_contents ("index.bel");
$replace_from = array ('$variable_a', '$variable_b');
$replace_to = array ($var_a_value, $var_b_value);
$index = str_replace($replace_from,$replace_to,$index);
Now that is for simple variable replace, but you soon want more tags, more functionality, and one way to do things like these are using preg_replace_callback. You might want to take a look at it, as it will eventually make possible to replace variables, include other files {include:file.bel}, replace text like {img:foo.png}.
EDIT: reading more your comments, you are on your way to create own framework. Take a look at preg_replace_callback as it gives you more ways to handle things.
Very simple example here:
...
$index = preg_replace_callback ('/{([^}]+)}>/i', 'preg_callback', $index);
...
function preg_callback($matches) {
var_dump($matches);
$s = preg_split("/:/",$matches[1]); // string matched split by :
$f = 'func_'.strtolower($s[0]); // all functions are like func_img,func_include, ...
$ret = $f($s); // call function with all split parameters
return $ret;
}
function func_img($s) {
return '<img src="'.$s[1].'" />';
}
From here you can improve this (many ways), for example dividing all functionalities to classes, if you want.
Yes, this is possible, but why are you making your own framework? The code you provided clearly looks like Smarty Template. You could try to look how they did it.
A possible way to run those code is splitting them into pieces. You split on the dollar sign and the next symbol which is not an underscore, a letter or an number. Once you did that. You could parse it into a variable.
$var = 'variable_name'; // Split it first
echo $$var; // Get the given variable
Did you mean something like this?