Match and replace placeholders in a string - php

I am working on a small CMS which takes a developer stdClass object and processes it accordingly. The stdClass contains arrays and other objects. One of these objects is a variables object. There maybe lots of variables objects.
I will just explain this instead of showing the code to make it less confusing. The developer specifies a variable and a set of values that may go into that variable. The values that the user specifies maybe multidimensional arrays. This is an example of how the variables object is created:
//Add variable1
$variable = $variables[] = new stdClass;
$variable->name = 'var1'; $variable->generator = 'function'; $variable->value = 'v'; $variable->enum = array (array('Mars', 9.8), array('Earth', 3.77)); $variable->description; $variable->callback = 'callback_function';
//Add variable2
$variable = $variables[] = new stdClass;
$variable->name = 'var1'; $variable->generator = 'function'; $variable->value = 'v'; $variable->enum = array (array('Mars', 9.8), array('Earth', 3.77)); $variable->description; $variable->callback = 'callback_function';
At some point in the stdClass the developer has to specify where the variables should be placed. The placeholder template looks like this: $variables[0] which selects the first variable or $variables[0][1] which selects the first variable and then the first element in that variable. I hope that makes sense.
I have to come up with a php algorithm that go through a piece of text and replace all the placeholders with the correct values.
My solution
Get all the variables->value into a new array. I have done this successfully.
Get all the placeholders in a piece of text. I am stuck at this point. I don't use regular expressions much.
I started by using:
preg_match_all('/\$variables[[0-9a-zA-Z]+]/', $text, $matched_placeholders);
..but this will only match $variables[0] and I am tring to expand this to match variations such as: $variables[0][1] or $variables[0][2][0], etc.
Once I have the placeholders into an array and the variables values into another array. I can do a foreach loop and replace all the placeholders.
Any advice will be appreciated. What regular expression pattern should I use to match this $variables[0][2][0]...

Your preg_match_all function will look something like:
preg_match_all('/\$variables((\[[0-9a-zA-Z]+\])*)/', $text, $matched_placeholders);
This will match:
$variables
$variables[#]
$variables[#][#]
and so on
And will store the [#][#][#]... portion in $matched_placeholders[1]
Test with $text = '$variables[0][1] or $variables[0][2][0]';:
Array (
[0] => Array (
[0] => $variables[0][1]
[1] => $variables[0][2][0]
)
[1] => Array (
[0] => [0][1]
[1] => [0][2][0]
) // The rest is just "noise"
[2] => Array ( [0] => [1] [1] => [0] )
)
If, for example, you wanted to rename your variable (since I have no idea what you're actually trying to do but just helping you with the regex part), you could do:
$text = preg_replace('/\$variables((\[[0-9a-zA-Z]+\])*)/', '\$newvar$1', $text);
which would replace all occurences of $variables with $newvar.

This will work :-
str.replaceAll( , );

Related

How to get part of the string from an array element, and insert it into another array?

I have an array which returns something like this:
[44] => 165,text:Where is this city:,photo:c157,correct:0,answers:[{text:Pery.,correct:true},{text:Cuba.,correct:false},{text:Brazil.,correct:false}]},{
I would like to get all the numbers from the beginning of the string until the first occurrence of a comma in the array element value. In this case that would be number 165 and I want to place that number in another array named $newQuesitons as key questionID
Next part will be to get the string after the first occurrence of : until the next occurrence of : and add it into the same array ($newQuestions) as key question.
Next part will be the photo:, that is I need to get the string after the photo: until the next occurrence of the comma, in this case peace of the string extracted will be c157.
I would like to add that as new key named photo in the array $newQuestions
I think this may be able to help you
<?php
$input = '165,text:Where is this city:,photo:c157,correct:0';
//define our new array
$newQuestions = Array();
//first part states we need to get all the numbers from the beginning of the string until the first occurence of a ',' as this is our array key
//$arrayKey[0] is our arrayKey
$arrayKey = explode(',',$input);
//second part requires us to loop through the array and split up the strings by comma and colon
foreach($arrayKey as $data){
//split each text into 2 by the colon
$item = explode(':',$data);
//we are only interested in items that have a colon in them, if we split it and the input has no colon, the count would be 0, so this check is used to ignore those
if(count($item) > 0) {
//now we can build our array
$newQuestions[$arrayKey[0]][$item[0]] = $item[1];
}
}
//output array
print_r($newQuestions);
?>
I don't fully understand the inputted array so the code above will most likely have to be tweaked, but atleast it gives you some logic to go from.
The output of this was: Array ( [165] => Array ( [165] => [text] => Where is this city [photo] => c157 [correct] => 0 ) )
I get my own solution, at least for the part of the problem. I manage to get the questionID using the following code:
$newQuestions = array();
foreach ($arrQuestions as $key => $question) {
$substring = substr($question, 0, strpos($question, ','));
$newQuestions[]['questionID'] = $substring;
}
I am now trying to do the same thing for the question part. I will update this code in case that someone else may have similar task to accomplish.

php challenge: parse pseudo-regex

I have a challenge that I have not been able to figure out, but it seems like it could be fun and relatively easy for someone who thinks in algorithms...
If my search term has a "?" character in it, it means that it should not care if the preceding character is there (as in regex). But I want my program to print out all the possible results.
A few examples: "tab?le" should print out "table" and "tale". The number of results is always 2 to the power of the number of question marks. As another example: "carn?ati?on" should print out:
caraton
caration
carnaton
carnation
I'm looking for a function that will take in the word with the question marks and output an array with all the results...
Following your example of "carn?ati?on":
You can split the word/string into an array on "?" then the last character of each string in the array will be the optional character:
[0] => carn
[1] => ati
[2] => on
You can then create the two separate possibilities (ie. with and without that last character) for each element in the first array and map these permutations to another array. Note the last element should be ignored for the above transformation since it doesn't apply. I would make it of the form:
[0] => [carn, car]
[1] => [ati, at]
[2] => [on]
Then I would iterate over each element in the sub arrays to compute all the different combinations.
If you get stuck in applying this process just post a comment.
I think a loop like this should work:
$to_process = array("carn?ati?on");
$results = array();
while($item = array_shift($to_process)) {
$pos = strpos($item,"?");
if( $pos === false) {
$results[] = $item;
}
elseif( $pos === 0) {
throw new Exception("A term (".$item.") cannot begin with ?");
}
else {
$to_process[] = substr($item,0,$pos).substr($item,$pos+1);
$to_process[] = substr($item,0,$pos-1).substr($item,$pos+1);
}
}
var_dump($results);

read array from string php

I have a string like this
$php_string = '$user["name"] = "Rahul";$user["age"] = 12;$person["name"] = "Jay";$person["age"] = 12;';
or like this
$php_string = '$user = array("name"=>"Rahul","age"=>12);$person= array("name"=>"Jay","age"=>12);';
I need to get the array from the string ,
Expected result is
print_r($returned);
Array
(
[name] => Rahul
[age] => 12
)
Please note that there may be other contents on the string including comments,other php codes etc
Instead of relying on some magical regular expression, I would go a slightly easier route and use token_get_all() to tokenize the string and create a very basic parser that can create the necessary structures based on both array construction methods.
I don't think many people have rolled this themselves but it's likely the most stable solution.
use a combination of eval and preg_match_all like so:
if(preg_match_all('/array\s*\(.*\)/U', $php_string, $arrays)){
foreach($arrays as $array){
$myArray = eval("return {$array};");
print_r($myArray);
}
}
That will work as long as your array doesn't contain ) but can be modified further to handle that case
or as Jack suggests use token_get_all() like so:
$tokens = token_get_all($php_string);
if(is_array($tokens)){
foreach($tokens as $token){
if($token[0] != T_ARRAY)continue;
$myArray = eval("return {$token[1]};");
print_r($myArray);
}
}

An array is ending with a character(")") inside array element value, not with actual array end

An array which is populated it's value from database. when I print_r the array . It shows like below...
Array
(
[term] => These are following selection a) new b) old
)
Here the array is ending with character ) inside the term element " ..selection a) new ..", while it's only a character in the array. So How I would avoid the ending of array with charcters present inside the array ?
What you're viewing is the output of an array with print_r.
Defining an array in PHP is a little different:
$variable = array('inside First a) new, b) old');
print_r($variable);
var_dump($variable); // similar to print_r
There is also another way of doing that:
$variable = array();
$variable[0] = 'inside First a) new, b) old';
So you need to quote your value to get a string.
The array value in your declaration should be a string:
$myArray = array(
0 => 'inside First a) new , b) old';
);
In PHP you need to quote string values:
$array = array(
0 => 'inside First a) new , b) old'
);
See the manual. To be honest this is pretty basic stuff. If you don't know this, I'd suggest going away and getting a basic introduction to PHP book and reading through it...

php array processing question

Before I write my own function to do it, is there any built-in function, or simple one-liner to convert:
Array
(
[0] => pg_response_type=D
[1] => pg_response_code=U51
[2] => pg_response_description=MERCHANT STATUS
[3] => pg_trace_number=477DD76B-B608-4318-882A-67C051A636A6
)
Into:
Array
(
[pg_response_type] => D
[pg_response_code] =>U51
[pg_response_description] =>MERCHANT STATUS
[pg_trace_number] =>477DD76B-B608-4318-882A-67C051A636A6
)
Just trying to avoid reinventing the wheel. I can always loop through it and use explode.
I can always loop through it and use explode.
that's what you should do.
Edit - didn't read the question right at all, whoops..
A foreach through the array is the quickest way to do this, e.g.
foreach($arr as $key=>$val)
{
$new_vals = explode("=", $val);
$new_arr[$new_vals[0]] = $new_vals[1];
}
This should be around five lines of code. Been a while since I've done PHP but here's some pseudocode
foreach element in the array
explode result on the equals sign, set limit = 2
assign that key/value pair into a new array.
Of course, this breaks on keys that have more than one equals sign, so it's up to you whether you want to allow keys to have equals signs in them.
You could do it like this:
$foo = array(
'pg_response_type=D',
'pg_response_code=U51',
'pg_response_description=MERCHANT STATUS',
'pg_trace_number=477DD76B-B608-4318-882A-67C051A636A6',
);
parse_str(implode('&', $foo), $foo);
var_dump($foo);
Just be sure to encapsulate this code in a function whose name conveys the intent.

Categories