Convert string into array using php - php

I am trying to generate the array structure as coding style so it can be used for further development for that purpose i have used following:
function convertArray($string)
{
$finalString = var_export($string, true);
return stripslashes($finalString);
}
It worked fine but the problem is that it adds the additional quotes to the start and end of the value how can i remove these quotes.
Example generated string is as follows:
array (
'foo' => 'array('foo','bar','baz')',
'bar' => 'array('foo','bar')',
'baz' => 'array('foo','bar')',
);
The string i need is:
array (
'foo' => array('foo','bar','baz'),
'bar' => array('foo','bar'),
'baz' => array('foo','bar'),
);
UPDATE
Here is how i create my array:
foreach( $attributes as $attrib )
{
if( $attrib->primary_key == '1' )
$column[$attrib->name] = array("'$attrib->type'", "'$attrib->max_length'", '\'pk\'');
else
$column[$attrib->name] = array("'$attrib->type'", "'$attrib->max_length'");
$string[$attrib->name] = 'array('.implode(',', $column[$attrib->name]).')';
}
after processing from this loop the final array sent to the above function to convert it into my desired form/

And you can use backslashes
$string = "Some text \" I have a double quote";
$string1 = 'Second text \' and again i have quote in text';
And lost variant
You can use 1 idiot variant to create many lines string an in example:
$string = <<<HERE
Many many text
HERE;
But i dont recommend use this variant

try to use trim.
Example:
$string = "'text with quotes'";
echo $string; // output: 'text with quotes'
echo trim($string, array("'")); // output: text with quotes

Related

How to convert a string to point to a value in an array

I have a dynamically generated array. It is an associative array containing one or more sub-arrays. I also have a variable that dynamically generates a string value that should match an address within that array. How can use that string to retrieve the value at the corresponding address within the array? eg
<?php
$array = [ 'foo' => 'bar', 'x' => 0, 'y' => 'seven', 'tuppence' => [ 'price' =>'thruppence' ]];
$string = "$array['foo']";
$value = $string;
In this particular instance $value should = 'bar'. but it currently has the value "$array['foo']". The value of $string is dynamically generated, so on other occasions $string may = "$array['x']", in which case, $value should = 0; not "$array['x']"
I have tried making the string a reference, ie:
$value = &$string;
or including braces, eg:
$string = "{$array}['foo']";
or
$string = "($array['foo']}";
but nothing seems to work, by which I mean that PHP still treats $string as a string of meaningless text, rather than a reference pointing to an actual value at the corresponding address within an existing array, ie
print_r( $array);
produces a print out of the array.
In summary, I am asking: how do I change the expression:
$value = $string;
to make $value actually become the value at the corresponding address within $array?
use curly brackets as such "{$arr['key']}"
$array = [ 'foo' => 'bar' ];
$string = "{$array['foo']}";
$value = $string;
Isn't this working?
$array = [ 'foo' => 'bar' ];
$string = &$array['foo'];
String must be the address of the array key

Shortcode style parsing

Looking at how WP uses shortcodes I thoufght I could implement the same structure into a project, I assumed this would be availble somwehere but have yet to track down.
I started to parse myself starting with a preg_match_all
preg_match_all('/[[^]]*]/', $content, $match);
and that return the array with all the shortcodes inside content as expected but then looking at parsing the name, variables or array keys with values I start getting real heavy on parsing.
My current thought is to break up on spaces, then parse each but then i run into spaces in the values even though they are in quotes. So if i parse quoted data first then spaces to re-construct it seems very wasteful. I don't need to re-invent the wheel here so any input is fantastic.
example
[shortcodename key1="this is a value" key2="34"]
would like to have
Array
(
[shortcodename] => Array
(
[key1] => this is a value
[key2] => 34
)
)
here is the complete function that is working if anyone else is looking to do the same, obviously this is not meant to run user content but the called function should do any checks as this only replaces the shortcode if the funtction has a return value.
function processShortCodes($content){ // locate data inside [ ] and
//process the output, place back into content and returns
preg_match_all('/\[[^\]]*\]/', $content, $match);
$regex = '~"[^"]*"(*SKIP)(*F)|\s+~';
foreach ($match[0] as $key => $val){
$valOrig = $val; // keep uncleaned value to replace later
$val = trim(substr($val, 1, -1));
$replaced = preg_replace($regex,":",$val);
$exploded = explode(':',$replaced);
if (is_array($exploded)){
$fcall = array();
$fcallName = array_shift($exploded); // function name
if (function_exists($fcallName)){ // If function exsist then go
foreach ($exploded as $aKey => $aVal){
$arr = explode("=", $aVal);
if (substr($arr[1], 0, 1) == '&'){
$fCall[$arr[0]]=substr($arr[1], 6, -6); // quotes can be "
}else{
$fCall[$arr[0]]=substr($arr[1], 1, -1);
}
}
if ( is_array($fCall) && $fcallName ){
$replace = call_user_func($fcallName, $fCall);
if ($replace){
$content = str_replace($valOrig,$replace,$content);
}
}
}
}
}
You can try this to change all spaces not wrapped in quotes to let's say a semicolon then explode by semicolon
$regex = '~"[^"]*"(*SKIP)(*F)|\s+~';
$subject = 'hola hola "pepsi cola" yay';
$replaced = preg_replace($regex,";",$subject);
$exploded = explode(';', $replaced);
Credits

Dynamic str_replace vars (without knowing the name)

I have a DB with pages with some variabiles in the content, for exmpale [var1], [name], [foo],..
Example of page:
hi [name],
are you [var1] or [foo]?
All these variables should be replaced with the corrisponding php variabiles on output
[var1] become $var1
[name] become $name
I know that i can use str_replace manually to change this variabiles, for example:
echo( str_replace( array( [var1], [name], [foo] ), array( $var1, $name, $foo), $page ));
But there is a way to create a loop that automatically replaces all these vars?
Let us consider an array containing some string as follows:
array("var1","name","foo")
So here is the solution:
<?php
$rowdata=array("var1","name","foo");
foreach($rowdata as $key=>$value){
$rowdata[$key]="$".$value;
}
echo '<pre>';
print_r($rowdata);
echo '</pre>';
?>
Try this code. It is working. First of all find all such strings which are in bracket. and then use the preg_replace to replace the content.
$text = '[This] is a [test] string, [try] it.';
preg_match_all("^\[(.*?)\]^", $text, $matches);
$data = array_combine($matches[1],$matches[1]);
foreach($data as $key =>$value)
{
$text = preg_replace('/\['.$key.'\]/', '$'.$value, $text);
}
echo $text;

Create Array out of a plain text variable?

I am trying to create an array from a plain text variable like so in php:
$arraycontent = "'foo', 'bar', 'hallo', 'world'";
print_r( array($arraycontent) );
But it outputs the entire string as [0]
Array ( [0] => 'foo', 'bar', 'hallo', 'world' )
I would like 'foo' to be [0]
bar to be [1] and so on. Any pointers? Is this even possible?
YIKES, why are these all so long?
Here's a one liner:
explode("', '", trim($arraycontent, "'"));
If your string was like this:
$arraycontent = "foo, bar, hallo, world"
With only the commas separating, then you could use explode, like this:
$myArray = explode(", ", $arraycontent);
This will create an array of strings based on the separator you define, in this case ", ".
If you want to keep the string as is, you can use this:
$myArray = explode("', '", trim($arraycontent, "'"));
This will now use "', '" as the separator, and the trim() function removes the ' from the beginning and end of the string.
If this is PHP you could use:
$foo = "'foo', 'bar', 'hallo', 'world'";
function arrayFromString($string){
$sA = str_split($string); array_shift($sA); array_pop($sA);
return explode("', '", implode('', $sA));
}
print_r(arrayFromString($foo));
eval('$array = array('.$arraycontent.');');
Would be the shortest way.
$array = explode(',', $arraycontent);
$mytrim = function($string) { return trim($string, " '"); };
$array = array_map($mytrim, $array);
A safer and therefore better one. If you have different whitespace characters you would have to edit the $mytrim lambda-function.
Here is a variant that based on the input example would work, but there might be corner cases that is not handled as wanted.
$arraycontent = "'foo', 'bar', 'hallo', 'world'";
$arrayparts = explode(',', $arraycontent); // split to "'foo'", " 'bar'", " 'hallo'", " 'world'"
for each ($arrayparts as $k => $v) $arrayparts[$k] = trim($v, " '"); // remove single qoute and spaces in beggning and end.
print_r( $arrayparts ); // Array ( [0] => 'foo', [1] => 'bar', [2] => 'hallo', [3] => 'world' )
This should give what you want, but also note that for example
$arraycontent = " ' foo ' , ' bar ' ' ' ' ', 'hallo', 'world'";
Would give the same output, so the question then becomes how strict are the $arraycontentinput?
If you have to have input like this, I suggest trimming it and using preg_split().
$arraycontent = "'foo', 'bar', 'hallo', 'world'";
$trimmed = trim($arraycontent, " \t\n\r\0\x0B'\""); // Trim whitespaces and " and '
$result = preg_split("#['\"]\s*,\s*['\"]#", $trimmed); // Split that string with regex!
print_r($result); // Yeah, baby!
EDIT: Also I might add that my solution is significantly faster (and more universal) than the others'.
That universality resides in:
It can recognize both " and ' as correct quotes and
It ignores the extra spaces before, in and after quoted text; not inside of it.
Seems you are having problem while creating an array..
try using
<?php
$arraycontent = array('foo', 'bar', 'hallo', 'world');
print_r( array($arraycontent) );
?>
its output will be:
Array ( [0] => Array ( [0] => foo [1] => bar [2] => hallo [3] => world
) )

Search an Array and remove entry if it doesn't contain A-Z or a A-Z with a dash

I have the following Array:
Array
(
[0] => text
[1] => texture
[2] => beans
[3] =>
)
I am wanting to get rid of entries that don't contain a-z or a-z with a dash. In this case array item 3 (contains just a space).
How would I do this?
Try with:
$input = array( /* your data */ );
function azFilter($var){
return preg_match('/^[a-z-]+$/i', $var);
}
$output = array_filter($input, 'azFilter');
Also in PHP 5.3 there is possible to simplify it:
$input = array( /* your data */ );
$output = array_filter($input, function($var){
return preg_match('/^[a-z-]+$/i', $var);
});
Try:
<?php
$arr = array(
'abc',
'testing-string',
'testing another',
'sdas 213',
'2323'
);
$tmpArr = array();
foreach($arr as $str){
if(preg_match("/^([-a-z])+$/i", $str)){
$tmpArr[] = $str;
}
}
$arr = $tmpArr;
?>
Output:
array
0 => string 'abc' (length=3)
1 => string 'testing-string' (length=14)
For the data you have provided in your question, use the array_filter() function with an empty callback parameter. This will filter out all empty elements.
$array = array( ... );
$array = array_filter($array);
If you need to filter the elements you described in your question text, then you need to add a callback function that will return true (valid) or false (invalid) depending on what you need. You might find the ctype_alpha functions useful for that.
$array = array( ... );
$array = array_filter($array, 'ctype_alpha');
If you need to allow dashes as well, you need to provide an own function as callback:
$array = array( ... );
$array = array_filter($array, function($test) {return preg_match('(^[a-zA-Z-]+$)', $test);});
This sample callback function is making use of the preg_match() function using a regular expression. Regular expressions can be formulated to represent a specifc group of characters, like here a-z, A-Z and the dash - (minus sign) in the example.
Ok , simply you can loop trough the array. Create an regular expression to test if it matches your criteria.If it fails use unset() to remove the selected element.

Categories