Create Array out of a plain text variable? - php

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
) )

Related

Querystring parameter explode str_replace array works for only 1 of the delimiters

I am using a explode and str_replace on the get parameter of the query string URL. My goal is to split the strings by certain characters to get to the value in the string that I want. I am having issues. It should work but doesn't.
Here are two samples of links with the query strings and delimiters I'm using to str_replace.
http://computerhelpwanted.com/jobs/?occupation=analyst&position=data-analyst
as you can see the URL above parameter is position and the value is data-analyst. The delimiter is the dash -.
http://computerhelpwanted.com/jobs/?occupation=analyst&position=business+systems+analyst
and this URL above uses same parameter position and value is business+systems+analyst. The delimiter is the + sign.
The value I am trying to get from the query string is the word analyst. It is the last word after the delimiters.
Here is my code which should do the trick, but doesn't for some reason.
$last_wordPosition = str_replace(array('-', '+')," ", end(explode(" ",$position)));
It works if the delimiter is a + sign, but fails if the delimiter is a - sign.
Anyone know why?
You have things in the wrong order:
$last_wordPosition = end(explode(" ", str_replace(array('-', '+'), " ", $position)));
You probably want to split it up so as to not get the E_STRICT error when not passing an variable to end:
$words = explode(" ", str_replace(array('-', '+'), " ", $position));
echo end($words);
Or something like:
echo preg_replace('/[^+-]+(\+|-)/', '', $position);
As #MarkB suggested you should use parse_url and parse_str since it is more appropriate in your case.
From the documentation of parse_url:
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
From the documentation of parse_str:
Parses str as if it were the query string passed via a URL and sets variables in the current scope.
So here is what you want to do:
$url1 = 'http://computerhelpwanted.com/jobs/?occupation=analyst&position=data-analyst';
$url2 = 'http://computerhelpwanted.com/jobs/?occupation=analyst&position=business+systems+analyst';
function mySplit($str)
{
if (preg_match('/\-/', $str))
$strSplited = split('-', $str);
else
$strSplited = split(' ', $str);
return $strSplited;
}
parse_str(parse_url($url1)['query'], $output);
print_r($values = mySplit($output['position']));
parse_str(parse_url($url2)['query'], $output);
print_r($values = mySplit($output['position']));
OUTPUT
Array
(
[0] => data
[1] => analyst
)
Array
(
[0] => business
[1] => systems
[2] => analyst
)
You said that you needed the last element of those values. Therefore you could find end and reset useful:
echo end($values);
reset($values);
Answering my own question to show how I ended up doing this. Seems like way more code than what the accepted answer is, but since I was suggested to use parse_url and parse_str but couldn't get it working right, I did it a different way.
function convertUrlQuery($query) {
$queryParts = explode('&', $query);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
return $params;
}
$arrayQuery = convertUrlQuery($_SERVER['QUERY_STRING']); // Returns - Array ( [occupation] => designer [position] => webmaster+or+website-designer )
$array_valueOccupation = $arrayQuery['occupation']; // Value of occupation parameter
$array_valuePosition = $arrayQuery['position']; // Value of position parameter
$split_valuePosition = explode(" ", str_replace(array('-', '+', ' or '), " ", $array_valuePosition)); // Splits the value of the position parameter into separate words using delimeters (- + or)
then to access different parts of the array
print_r($arrayQuery); // prints the array
echo $array_valueOccupation; // echos the occupation parameters value
echo $array_valuePosition; // echos the position parameters value
print_r($split_valuePosition); // prints the array of the spitted position parameter
foreach ($split_valuePosition as $value) { // foreach outputs all the values in the split_valuePosition array
echo $value.' ';
}
end($split_valuePosition); // gets the last value in the split_valuePosition array
implode(' ',$split_valuePosition); // puts the split_valuePosition back into a string with only spaces between each word
which outputs the following
arrayQuery = Array
(
[occupation] => analyst
[position] => data-analyst
)
array_valueOccupation = analyst
array_valuePosition = data-analyst
split_valuePosition = Array
(
[0] => data
[1] => analyst
)
foreach split_valuePosition =
- data
- analyst
end split_valuePosition = analyst
implode split_valuePosition = data analyst

Strings and Arrays not working like I thought

I'm trying to learn more about strings and arrays. I have this bit of code:
<?php
$states = "OH, VA, GA";
$arrayStates = explode(",", $states);
$exists = "GA";
print_r($arrayStates);
if (in_array($exists, $arrayStates)){
echo "<br/>" . $exists . " " . "exists.";
} else {
echo "<br/>" . $exists . " " . "doesn't exist.";
}
?>
According to my feeble mind, GA should exist in the array. If I put $exists = "OH", that works. But the screen is showing this:
Array ( [0] => OH [1] => VA [2] => GA )
GA doesn't exist.
What am I not understanding here?
The array contains the string " GA" with a space as the first character. That's not equal to `"GA", which goesn't have a space.
You should either use explode(", "), $states) or call trim() on each element of the array:
$arrayStates = array_map('trim', explode(",", $states));
You need to explode with a space after the comma.
$arrayStates = explode(", ", $states);
you're splitting with , but your text has spaces, so after split you have:
Array ( [0] => OH [1] => _VA [2] => _GA )
you can either split by ,_ (replace underscore with space)
or you can trim all values after split, like:
foreach ($arrayStates as $k => $v) $arrayStates[$k] = trim($v);
That is because it is being divided by , so your array contents are :
Array
(
[0] => OH
[1] => VA
[2] => GA
)
you need to do $arrayStates = explode(", ", $states);
In $arrayStates after applying explode(...) you have:
$arrayStates[0] stores "OH"
$arrayStates[1] stores " VA"
$arrayStates[2] stores " GA"
Note at index 2 the array is storing " GA" (note the space) instead of "GA" that is because in the explode function you are using ",". To get your code working as you want you should use in the explode function ", " (note the space)
The explode method splits the string on the comma "," ONLY and does not remove the whitespace. As a result you end up comparing "GA" (your $exists) to " GA" (inside of the array, note the whitespace) =]

Convert string into array using 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

RegEx in PHP to extract components of nquad

I'm looking around for a RegEx that can help me parse an nquad file. An nquad file is a straight text file where each line represents a quad (s, p, o, c):
<http://mysubject> <http://mypredicate> <http://myobject> <http://mycontext> .
<http://mysubject> <http://mypredicate2> <http://myobject2> <http://mycontext> .
<http://mysubject> <http://mypredicate2> <http://myobject2> <http://mycontext> .
The objects can also be literals (instead of uris), in which case they are enclosed with double quotes:
<http://mysubject> <http://mypredicate> "My object" <http://mycontext> .
I'm looking for a regex that given one line of this file, which will give me back a php array in the following format:
[0] => "http://mysubject"
[1] => "http://mypredicate"
[2] => "http://myobject"
[3] => "http://mycontext"
...or in the case where the double quotes are used for the object:
[0] => "http://mysubject"
[1] => "http://mypredicate"
[2] => "My Object"
[3] => "http://mycontext"
One final thing - in an ideal world, the regex will cater for the scenario there may be 1 or more spaces between the various components, e.g.
<http://mysubject> <http://mypredicate> "My object" <http://mycontext> .
I'm going to add another answer as an additional solution using only a regex and explode:
$line = "<http://mysubject> <http://mypredicate> <http://myobject> <http://mycontext>";
$line2 = '<http://mysubject> <http://mypredicate> "My object" <http://mycontext>';
$delimeter = '---'; // Can't use space
$result = preg_replace('/<([^>]*)>\s+<([^>]*)>\s+(?:["<]){1}([^">]*)(?:[">]){1}\s+<([^>]*)>/i', '$1' . $delimeter . '$2' . $delimeter . '$3' . $delimeter . '$4', $line);
$array = explode( $delimeter, $result);
It seems this can be accomplished as follows (I do not know your character restrictions so it may not work specifically for your needs, but worked for your test cases):
$line = "<http://mysubject> <http://mypredicate> <http://myobject> <http://mycontext>";
$line2 = '<http://mysubject> <http://mypredicate> "My object" <http://mycontext>';
// Remove unnecessary whitespace between entries (change $line to $line2 for testing)
$delimeter = '---';
$result = preg_replace('/([">]){1}\s+(["<]){1}/i', '$1' . $delimeter . '$2', $line);
// Explode on our delimeter
$array = explode( $delimeter, $result);
foreach( $array as &$a)
{
// Replace the characters we don't want with nothing
$a = str_replace( array( '<', '.', '>', '"'), '', $a);
}
var_dump( $array);
This regular expression would help:
/(\S+?)\s+(\S+?)\s+(\S+?)\s+(\S+?)\s+\./
(s, p, o, c) values will be in $1, $2, $3, $4 variables.

php change array format for url

I have a weird project I'm working on. I'm totally new to php so it has been a struggle so far.
I have a form that gives an array and posts it:
...
return($keywords);
}
$keywordlist = explode("\r\n", $keywordlist);
foreach($keywordlist as $keyword){
print_r(mixer(strtolower($keyword)));
}
I get this:
Array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six [6] => ....
But would like it to come out like this instead:
%28one%2Ctwo%2Cthree%2Cfour%2Cfive%2Csix%29
Ultimately hope to be able to attach it to the end of a url like ask.com search:
"http://www.ask.com/web?q=(put my keywords here)"
then navigate there
In theory it would be like I typed "(one,two,three,four,five,six)" into the search bar and pressed enter.
Hopefully that makes some sense.
Something like this:
$commaSeparated = implode(',', $array);
$withParens = '(' + $commaSeparated + ')';
$urlEncoded = urlencode($withParens);
print $urlEncoded;
Use the php implode() function.
So you could do this:
$array = new array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six );
$string = '%28'.implode( '%2C', $array ).'%29';
Now $string will be what you need
This code:
$keywords = array('one', 'two', 'three');
$query = '(' . implode(',', $keywords) . ')';
echo('Search query: ' . $query . PHP_EOL);
$query = rawurlencode($query);
echo('Encoded: ' . $query . PHP_EOL);
Gives this output:
Search query: (one,two,three) Encoded:
%28one%2Ctwo%2Cthree%29
$keywordlist = explode("\r\n", $keywordlist);
array_walk($keywordlist, 'strtolower');
$keywords = '('.implode(",", $keywordList).')';
print_ris what prints your array like this.
http://php.net/manual/en/function.print-r.php
How to solve it depends on a few things. What does mixer()do? And is the keywords always in lowercase? If mixer doens't do much and the keywords are in lowercase you could do something like:
$string = '%28' . implode('%2C',
$keyword) . '%29';
If it's URL encoding you are after you could use the function url_encode instead of manually adding encoded values as above.
Something like this?
$input = array('one', 'two', 'three');
$s = implode(',', $input);
$s = '('.$i.')';
print urlencode($s);
You could encode each part of the array using urlencode and then manually put it in your url (making a url string by yourself). http://php.net/manual/en/function.urlencode.php
Or you could use this function instead: http://php.net/manual/en/function.http-build-query.php

Categories