I am doing an assignment on how to take a string of text separated by commas and reverse the individual words and return the words in the same order.
This code does that but it is not returning it as a string for some reason and i do not understand.
<?php
function bassAckwards($input)
{
// YOUR CODE HERE
$commas = substr_count($input, ",");
$NumWords = ($commas + 1);
$words = array($input);
for($x=0;$x<$NumWords;$x++)
{
$answer = array(strrev($words[$x]));
$answer = implode(",",$answer);
print $answer;
}
}
?>
function bassAckwards($str){
$words = explode(',', $str);
$reversedWords = array_map('strrev', $words);
return implode(',', $reversedWords);
}
var_dump(bassAckwards('foo,bar,baz')); // string(11) "oof,rab,zab"
Save yourself some headaches and use the built-it functions.
explode
make 'foo,bar,baz' => array('foo','bar','baz')
array_map & strrev
Execute strrev (string reverse) on every element of the array with array_map and return the [modified] array back.
implode
convert the array back to a csv.
$reversedWords = array();
// Explode by commas
$words = explode(',', $input);
foreach ($word in $words) {
// For each word
// Stack it, reversed, in the new array $reversedWords
$reversedWords[] = strrev($word);
}
// Implode by commas
$output = implode(',', $reversedWords);
print $output;
Related
I have a string
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
Need to convert this string in below format.
$utmcsr = google;
$utmcmd= organic;
$utmccn= (not set);
$utmctr= (not provided);
and more can come. I have try explode and slip function but not gives result. Please suggest.
Thanks in advance
With "Double explode" you can extract all key-value pairs from the string. First, explode on the pipe symbol, the resuting array contains strings like utmcsr=google. Iterate over this array and explode each string on the equal sign:
$result = [];
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
$arr = explode('|', $str);
foreach($arr as $str2) {
$values = explode('=', $str2);
$result[ $values[0] ] = $values[1];
}
Try this one
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
$new_array = explode('|', $str);
$result_array = array();
foreach ($new_array as $value) {
$new_arr = explode('=', $value);
$result_array[$new_arr[0]] = $new_arr[1];
}
extract($result_array);
echo $utmcsr;
echo $utmctr;
Output: google(not provided)
i am working on a module where i have stored string in a column separated by comma(,) and i have split the string into an array and added the array into drop down, but when i am doing this with multiple columns, its not sorting the array in dropdown
here is the code
$pp=DB::table('gcp_projects')->where('niche','!=',' ')->where('niche','!=','')->where('niche','!=',null)->orderBy('niche')->pluck('niche');
$testing=explode(",",$pp);
$arr=array();
$tttt=array();
for($i=0;$i<=count($pp);$i++)
{
$arr= explode(",",$pp);
$temp = preg_replace("/[^a-zA-Z 0-9]+/", "", $arr);
$tttt=array_unique($temp);
sort($tttt);
}
<?php
// Use preg_split() function
$string = "123,456,78,000";
$str_arr = preg_split ("/\,/", $string);
print_r($str_arr);
// use of explode
$string = "123,46,78,000";
$str_arr = explode (",", $string);
print_r($str_arr);
?>
you can do it like this and use sort option like
$values = array ("zercggj.co.uk", "lkjhg.org.au", "qqxze.org.au",
"bfhgj.co.uk", "sdfgh.org.uk");
echo "<br>input:<br>";
foreach ($values as $host) echo "$host<br>";
// create a suitable structure
foreach ($values as $host)
{
$split = explode('.', $host, 2);
$printable[$split[1]][] = $split[0];
}
// sort by domains
asort ($printable);
// output
echo "<br>sorted:<br>";
foreach ($printable as $domain => $hosts)
{
echo "domain: $domain<br>";
// sort hosts within the current domain
asort ($hosts);
// display them
foreach ($hosts as $host)
echo "--- $host<br>";
}
So Far i found this solution which is working for me
$pp=DB::table('gcp_projects')->whereNotNull('niche')->orderBy('niche')->pluck('niche')->toArray();
$aa=implode(',',$pp);
$myArray = explode(',', $aa);
$im=implode(' ',$myArray);
$ex=explode(' ',$im);
$tttt=array_unique($ex);
sort($tttt);
$str = preg_replace("/[^a-zA-Z 0-9]+/", "", $tttt);
$result = array_filter($str);
you have to mention orderby ASC OR DESC
orderBy('created_at', 'asc') Or orderBy('created_at', 'asc')
I have string like this
$string = 'title,id,user(name,email)';
and I want result to be like this
Array
(
[0] => title
[1] => id
[user] => Array
(
[0] => name
[1] => email
)
)
so far I tried with explode function and multiple for loop the code getting ugly and i think there must be better solution by using regular expression like preg_split.
Replace the comma with ### of nested dataset then explode by a comma. Then make an iteration on the array to split nested dataset to an array. Example:
$string = 'user(name,email),office(title),title,id';
$string = preg_replace_callback("|\(([a-z,]+)\)|i", function($s) {
return str_replace(",", "###", $s[0]);
}, $string);
$data = explode(',', $string);
$data = array_reduce($data, function($old, $new) {
preg_match('/(.+)\((.+)\)/', $new, $m);
if(isset($m[1], $m[2]))
{
return $old + [$m[1] => explode('###', $m[2])];
}
return array_merge($old , [$new]);
}, []);
print '<pre>';
print_r($data);
First thanks #janie for enlighten me, I've busied for while and since yesterday I've learnt a bit regular expression and try to modify #janie answer to suite with my need, here are my code.
$string = 'user(name,email),title,id,office(title),user(name,email),title';
$commaBetweenParentheses = "|,(?=[^\(]*\))|";
$string = preg_replace($commaBetweenParentheses, '###', $string);
$array = explode(',', $string);
$stringFollowedByParentheses = '|(.+)\((.+)\)|';
$final = array();
foreach ($array as $value) {
preg_match($stringFollowedByParentheses, $value, $result);
if(!empty($result))
{
$final[$result[1]] = explode('###', $result[2]);
}
if(empty($result) && !in_array($value, $final)){
$final[] = $value;
}
}
echo "<pre>";
print_r($final);
$word = file('list.txt');
$content = file_get_contents('fleetyfleet.txt');
fleetyfleet.txt contains
DimensionNameGreenrandomjunktextextcstuffidonwantDimensionNameBluemoreeecrapidontwannaseeeDimensionNameYellowDimensionNameGrayrandomcrapDimensionNameRed
list.txt contains
Green Blue Yellow
what i want is to be able to find DimensionName then store the word after it into an array if the word is in list.txt
so when script was ran the result stored in array would be Green,Blue,Yellow but not Red and Gray because they are not in our list
Explode your word list, then loop over it:
$word = file_get_contents('list.txt');
$content = file_get_contents('fleetyfleet.txt');
$found_dimensions = array(); // our array
$word_array = explode(' ', $word); // explode the list
foreach($word_array as $one_word) { // loop over it
$str = 'DimensionName'.$one_word; // what are we looking for?
if(strstr($content, $str) !== false) { // look for it!
echo "Found $one_word<br/>"; // Just for demonstration purposes
$found_dimensions[] = $one_word; // add to the array
}
}
The trick is to explode() your file contents by delimiter and then filter results with the words from the list. $matching contains all found fragments matching list.
$words = file_get_contents('list.txt');
$text = file_get_contents('content.txt');
$elements = explode('DimensionName', $text); // trick
$words = explode(' ', $words); // words list
// leverage native PHP function
$matching = array_reduce($elements, function($result, $item) use($words) {
if(in_array($item, $words)) { $result[] = $item; }
return $result;
}, array());
var_dump($matching);
UPDATE
array_reduce() is a neat function, but I totally forgot about a way simpler solution:
$matching = array_intersect($words, $elements);
From the docs:
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
So $matching will contain all elements from $words array that are present in $elements. This is the simplest and possibly the best solution here.
I think this is what you wanted..I loop through each word in list.txt, and then use a preg_match() to see if that dimension is in fleetyfleet.txt (you don't need a regex for my example, but I left it in case your example is more complicated). If it matches, then I add the match to your array of $dimensions.
<?php
$dimensions = array();
$content = 'DimensionNameGreenrandomjunktextextcstuffidonwantDimensionNameBluemoreeecrapidontwannaseeeDimensionNameYellowDimensionNameGrayrandomcrapDimensionNameRed';
$list = 'Green Blue Yellow';
foreach(explode(' ', $list) as $word) {
if(preg_match('/DimensionName' . trim($word) . '/', $content, $matches) {
$dimensions[] = reset($matches);
}
}
var_dump($dimensions);
// array(3) {
// [0]=> string(18) "DimensionNameGreen"
// [1]=> string(17) "DimensionNameBlue"
// [2]=> string(19) "DimensionNameYellow"
// }
I am trying to call each string from an array. However, I am using this code to generate the array.
function extract_common_words($string, $stop_words, $max_count = 5) {
$string = preg_replace('/ss+/i', '', $string);
$string = trim($string); // trim the string
$string = preg_replace('/[^a-zA-Z -]/', '', $string); // Only take alphabet characters, but keep the spaces and dashes too…
$string = strtolower($string); // Make it lowercase
preg_match_all('/\b.*?\b/i', $string, $match_words);
$match_words = $match_words[0];
foreach ( $match_words as $key => $item ) {
if ( $item == '' || in_array(strtolower($item), $stop_words) || strlen($item) <= 3 ) {
unset($match_words[$key]);
}
}
$word_count = str_word_count( implode(" ", $match_words) , 1);
$frequency = array_count_values($word_count);
arsort($frequency);
//arsort($word_count_arr);
$keywords = array_slice($frequency,0);
return $keywords;
}
It returns an array which I can't seem to get the STRINGS from. So, I want to essentially take the results, and place them in a list which is an array of strings, with each string being the words, in consecutive order from most common to least common.
You can use the strtok function. Or else you can explode the string by whitespace. I hope that helps :)