I want to get the template words in a string. Template in the sense of words in {} inside a string. I am adding here a code to explain what I want exactly.
$string = "Hi {username}, Here is your {password}";
function get_template_variables($string)
{
....
....
return array();
}
$result = get_template_variables($string);
print_r($result);
array[
0 => username,
1 => password
]
I hope you understand what I need. I need the definition program to be used inside the get_template_variables($string) method
function get_template_variables($string) {
preg_match_all('/{([^}]+)}/', $string, $matches);
return $matches[1];
}
You can do:
function get_template_variables($string) {
if(preg_match_all('/\{(.*?)\}/',$string,$m)) {
return $m[1]
}
return array();
}
preg_match_all('/{.*}/U' , $string , $a );
where $result will be
array(1) {
[0]=>
array(2) {
[0]=>
string(10) "{username}"
[1]=>
string(10) "{password}"
}
}
Related
I am trying to iterate over a php object and changing each string value by reference, but something is just not working. In some arrays the strings will not be changed. Anyone has an idea why? Or has a suggestion on how to solve the task?
Here is my code:
recursive_object_string_changer($object);
function recursive_object_string_changer($object)
{
if($object == null) {
return;
}
foreach ($object as &$attribute) {
if (is_string($attribute)) {
$attribute = $attribute."!";
} else if (is_array($attribute)) {
recursive_object_string_changer($attribute);
} else if (is_object($attribute)) {
recursive_object_string_changer($attribute);
}
}
unset($attribute);
}
Thank you very much!
I think you want to make the function's signature also accept the initial object as a reference so that the recursion works on subsequent calls.
recursive_object_string_changer($object);
function recursive_object_string_changer(&$object)
{
if ($object === null) {
return;
}
foreach ($object as &$attribute) {
if (is_string($attribute)) {
$attribute .= "!";
} elseif (is_array($attribute)) {
recursive_object_string_changer($attribute);
} elseif (is_object($attribute)) {
recursive_object_string_changer($attribute);
}
}
unset($attribute);
}
I used this for a sample:
$object = new stdClass();
$object->string = 'Test';
$object->array = [
'a',
'b',
'c',
];
$subObject = new stdClass();
$subObject->string = 'Another String';
$object->object = $subObject;
Which produces:
object(stdClass)#1 (3) {
["string"]=>
string(5) "Test!"
["array"]=>
array(3) {
[0]=>
string(2) "a!"
[1]=>
string(2) "b!"
[2]=>
string(2) "c!"
}
["object"]=>
object(stdClass)#2 (1) {
["string"]=>
string(15) "Another String!"
}
}
You might always want to add a guard before the for loop to make sure that $object is an array or an object in the first place.
I have a lot of functions stored in an associative array like this :
$arr['my-title'] = function(){process(146,'My Title');};
$arr['un-cafe-chaud'] = function(){process(857,'Un café chaud');};
$arr['vpn'] = function(){process(932,'VPN');};
$arr['another-example'] = function(){process(464,'Another example');};
Currently I have to encode manually each key.
As the key name is function of the Title, I'd like to automate it.
function assign_keys($title,$id){
$u=str_replace(array(' ','é'),array('-','e'),strtolower($title));
$arr[$u] = function(){process($id,$title);};
}
But it doesn't work, as process function can't get $id and $title value.
Any help on how I could handle this would be highly appreciated ! Thank you.
First of all, you should pass $arr as argument to the function in order to be able to mutate it. Second, you should use use to make those two variables available in the anonymous function, like this:
function assign_keys($title,$id, &$arr){
$u=str_replace(array(' ','é'),array('-','e'),strtolower($title));
$arr[$u] = function() use ($id, $title){process($id,$title);};
}
Then use it like this:
$arr = [];
assign_keys('Some title', 123, $arr);
var_dump($arr);
This should print:
array(1) {
["some-title"]=>
object(Closure)#1 (1) {
["static"]=>
array(2) {
["id"]=>
int(123)
["title"]=>
string(10) "Some title"
}
}
}
You probably want a reference & to get the array outside of the function and use to get the variables into the closure:
function assign_keys($title, $id, &$arr){
$u = str_replace(array(' ','é'), array('-','e'), strtolower($title));
$arr[$u] = function() use($title, $id) { process($id, $title); };
}
assign_keys('My Title', 146, $arr);
I have an array that looks like this:
{"permissions":["1","2"]}
I'm trying to check if a given string is in the permissions array with the following function
function hasPermission($permission) {
return in_array($permission, array_column($this->permissions, 'permissions'));
}
When calling the function giving it the string "1" it return false even though 1 is in the permissions array
Any help would be appreciated
Thanks
EDIT
Here is a var Dump of the converted array
array(1) {
["permissions"]=>
array(2) {[0]=> string(1) "1"
[1]=> string(1) "2"
}
}
Try like this...
<?php
$json = '{"permissions":["1","2"]}';
$arr = json_decode($json,true);
print_r($arr);
echo in_array(1,$arr['permissions']); // returns 1 if exists
?>
So your function must be like this....
function hasPermission($permission) {
return in_array($permission, $this->permissions['permissions']);
}
array_column doesn't support 1D arrays, it returns an empty array if so.
Your $permissions array is 1D, so just use $this->permissions['permission'] to access it.
return in_array($permission, $this->permissions['permissions']);
Example:
$array = ['permissions' => ['1', '2']];
echo (int)in_array('1', array_column($array, 'permissions')); // 0
echo (int)in_array('1', $array['permissions']); // 1
Try this this will work.
$permission = json_decode('{"permissions":["1","2"]}',true);
echo "<pre>";print_r($permission);
if(is_array($permission)){
echo "this is an array";
}else{
echo "Not an array";
}
Thanks
i am trying to get this working: It is ment to return any function or method where the different 'functional parts' are subgrouped. I have problems with the maybe nested {..{.{} } } function body. At the moment the search breaks of after the first following }.
I do have a little bit a hard time understanding lock arround and recursive handling of Regs. So if someone would like to give a brief overall view - would be great!
i understand enough for this..The Regex:
to work with preg_* in PHP with "/im" set
([\w ]+)?(function)+([\s]+[\w\d]+)([\s]*?\(([^\)]+)?\))([\s]?\{+[^\}]*\})
Here a sample of use (i dont have named subpatterns on this sample...):
<?php
$s=file_get_contents('sometestcode');
$p='/
([\w ]+)?(function)+([\s]+[\w\d]+)([\s]*?\(([^\)]+)?\))([\s]?\{+[^\}]*\})
/im';
$m=array();
preg_match_all($p,$s,$m,PREG_SET_ORDER);
var_dump($m);
?>
Here comes the output as expected:
// Here the subject:
public static private function __set($name,$val){
$this->DATA[$name] = $val;
foreach( /*do it*/ ){
//work it...
}
return $this;
}
// The return
array(6){
[1]=>
string(7) "public static private " //makes sence, ha?
[2]=>
string(8) "function"
[3]=>
string(6) " __set" // func/meth name
[4]=>
string(12) "($name,$val)"
[5]=>
string(10) "$name,$val" // (if passed)$argument...
[6]=>
string(60) "{
$this->DATA[$name] = $val;
foreach( /*do it*/ ){
//work it...
}
// Here is the my link
// How to style the regExpPress??
}"
As title, I did it like below:
$array=array(0,1,2,3);
$result=array();
function makeArray($array,$result,$value){
$str='$result';
for ($i=0;$i<count($array);$i++){
$str.='['.$i.']';
}
$str.='="'.$value.'";';
eval($str);
return $result;
}
It can realize result when param $result is an empty array,but It report an error when $result is an array.
Error like :
Cannot use a scalar value as an array.
Anyways can realize it?
Thanks first!
Use pass by reference, not eval:
function makeArray($indexes, &$result, $value) {
$here =& $result;
foreach ($indexes as $i) {
if (!(isset($here[$i]) && is_array($here[$i]))) {
$here[$i] = array();
}
$here =& $here[$i];
}
$here = $value;
}
$array=array(0,1,2,3);
$result=array();
makeArray($array, $result, 3);
var_dump($result);
Output:
array(1) {
[0]=>
array(1) {
[1]=>
array(1) {
[2]=>
array(1) {
[3]=>
int(3)
}
}
}
}
Putting & before a function parameter means it will be passed by reference, so modifications to the variable inside the function will affect the original variable that was passed. And using =& in an assignment assigns a reference, so the target variable is an alias for the source.