I'm trying to create a string out of several array values like so:
$input = array("1140", "1141", "1142", "1144", "1143", "1102");
$rand_keys = array_rand($input, 2);
$str = "$input[$rand_keys[0]], $input[$rand_keys[1]]";
However, in the third line, I get this error:
Unexpected '[' expecting ']'
I thought that by converting the array to a value I would be able to use it in my string. What am I doing wrong with my syntax?
If you just want to fix your code, simply adjust that one line to this line:
$str = $input[$rand_keys[0]] .', '. $input[$rand_keys[1]];
Here are a couple of other nicer solutions:
shuffle($input);
$str = $input[0] .', '. $input[1];
Or:
shuffle($input);
$str = implode(', ',array_slice($input,0,2));
When you want to expand more than simple variables inside strings you need to use complex (curly syntax). Link to manual. You need to scroll down a little in the manual. Your last line of code will look like this:
$str = "{$input[$rand_keys[0]]}, {$input[$rand_keys[1]]}";
But you could also use implode to achieve the same result.
$str = implode(', ', [$rand_keys[0], $rand_keys[1]]);
It's up to you.
Related
I have a string ("$big_string") in php with is combination of small section of strings("$string") like this one "-val1(sec1)-", for eg :
$string1="-val1(sec1)-";
$string2="-val2(sec2)-";
$string3="-val3(sec3)-";
$big_string=$string1.$string2.$string3;
How can I separate values from $big_string to an array-like
the val1.. and so on values are between '-' & '('
and the sec1... and so on values are beteen '(' & ')-'
$array[0][0]="val1";
$array[0][1]="sec1";
$array[1][0]="val2";
$array[1][1]="sec2";
$array[2][0]="val3";
$array[2][1]="sec3";
Edit: I received the $big_string as input, above code is for ref that how $big_string is constructed.
You could use preg_match_all:
$string1 = "-val1(sec1)-";
$string2 = "-val2(sec2)-";
$string3 = "-val3(sec3)-";
$big_string = $string1 . $string2 . $string3;
if (preg_match_all('/-([^(]+)\(([^)]+)\)-/', $big_string, $matches, PREG_SET_ORDER)) {
$result = array_map(static fn($match) => array_slice($match, 1), $matches);
print_r($result);
}
If you're using PHP < 7.4, the line with $result can be changed into this:
$result = array_map(static function ($match) {
return array_slice($match, 1);
}, $matches);
Demo
I like to keep my code simple, using basic PHP functions. Something like this:
$big_string = '-val1(sec1)--val2(sec2)--val3(sec3)-';
$val_sec_array = explode('--', trim($big_string, '-'));
foreach ($val_sec_array as $val_sec) {
$array[] = [strstr($val_sec, '(', TRUE),
trim(strstr($val_sec, '('), '()')];
}
print_r($array);
The first line uses trim() to trim off the excess '-' at the begin and end of the $big_string and then explodes the remaining string into an array on each '--' it encounters.
The foreach loop then takes that array and uses strstr to first get the section before the '(' from the string and then the section after the '('. The '(' and ')' are then trimmed off the latter section. The two values then form an array [ ... , ... ] and are stored in the main array.
This is funny, saying it like this makes it sound more complex than it really is. Just look in the manual how this works:
explode()
trim()
foreach
strstr()
arrays
This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";
hi all i am trying to parse a big string and want to obtain only the value of id(id=dfsdfdsfdsfsaddfdfdfd) . My current code output extra data beyon the id value. could any one help me fix this problem.Thanks
preg_match_all("#live3.me.somesite.com([^<]+)\"#", $html, $foo);
print_r($foo[0]);
sample input string:
$html=".............."url":"rtmp:\/\/live3.me.somesite.com\/live\/?id=dfsdfdsfdsfsaddfdfdfd","name":"8.low.stream".........";
Is this an issue where you are set on using preg_match?
Or would something like 'parse_url' be acceptable?
http://php.net/manual/en/function.parse-url.php
Once parsed, getting specific query string parameters out should be easy
Just for the fun of answering an 8 month old question, here is my go at it :-)
We have got this to work with:
$html='".............."url":"rtmp:\/\/live3.me.somesite.com\/live\/?id=dfsdfdsfdsfsaddfdfdfd","name":"8.low.stream"........."';
That string sure looks a bit JSONish to me, so why not ...
// 1. Get rid of leading and trailing quotes and dots
$clean = trim($html, '"');
$clean = trim($clean, '.');
// 2. Add squiggly brackets to form a JSON string
$json = '{' . $clean . '}';
// 3. Decode the JSON into an array
$array = json_decode($json, true);
// 4. Parse URL value from the array and grab the query part
$query = parse_url($array['url'], PHP_URL_QUERY);
// 5. Get parameter values from the query
parse_str($query, $params);
// 6. Ta-da!
echo "Readable : ", $params['id'], PHP_EOL;
And of course ...
// The one-liner!
parse_str(parse_url(json_decode('{'.trim(trim($html,'"'),'.').'}', true)['url'], PHP_URL_QUERY), $params2);
echo "One-liner: ", $params2['id'], PHP_EOL;
Output:
Readable : dfsdfdsfdsfsaddfdfdfd
One-liner: dfsdfdsfdsfsaddfdfdfd
I have a string in an array like format.
["1","Data","time"] ["2","Data","time"] ["3","Data","time"] ["4","Data","time"]
I am trying to split the code after every ] - The data inside the [] could vary everytime so i cant use str_split();
I want to keep all the brackets in tack so they dont cut off so i cant use explode
Thank You
Easy regex:
$s = '["1","Data","time"] ["2","Data","time"] ["3","Data","time"] ["4","Data","time"]';
preg_match_all('/\[[^\]]+\]/', $s, $m);
print_r($m[0]);
But actually it's almost json, so:
$s = '["1","Data","time"] ["2","Data","time"] ["3","Data","time"] ["4","Data","time"]';
$s = '[' . str_replace('] [', '],[', $s) . ']';
print_r(json_decode($s));
Maybe you have a fragment or modified json, so it may be easier if you have actual json.
$str = '["1","Data","time"] ["2","Data","time"] ["3","Data","time"] ["4","Data","time"]';
$newStr = trim($str,'[');
$newStr1 = trim($newStr,']');
$arr = explode('] [',$newStr1);
print_r($arr);
Easiest solution (if you don't want regular expression) would be using trim 1 char from both sides and then explode by ']['.
Example:
$string = "[123][456][789]";
$string = substr($string,1,strlen($string)-1);
$array = explode('][',$string);
I want to concatenate one element of a multidimensional array with some strings.
<?
$string1 = 'dog';
$string2 = array
(
'farm' => array('big'=>'cow', 'small'=>'duck'),
'jungle' => array('big'=>'bear', 'small'=>'fox')
);
$string3 = 'cat';
$type = 'farm';
$size = 'big';
$string = "$string1 $string2[$type][$size] $string3";
echo($string);
?>
By using this syntax for $string, I get:
dog Array[big] cat
I would like not to use the alternate syntax
$string = $string1 . ' ' . $string2[$type][$size] . ' ' . $string3;
which works.
What's wrong with "$string1 $string2[$type][$size] $string3"?
Use the "complex syntax":
$string = "$string1 {$string2[$type][$size]} $string3";
PHP's variable parsing is quite simple. It will recognize one level array access, but not more level. By enclosing the expression in {} you explicitly state which part of the string is a variable.
See PHP - Variable parsing.
I'm not a fan of complex syntax, or variable parsing in strings. Normally I would use the "alternate" syntax you described. You could do this as well:
$string = implode(' ', array($string1, $string2[$type][$size], $string3));
Use this:
$string = "$string1 {$string2[$type][$size]} $string3";