Explode and assign it to a multi-dimensional array - php

I found this code in another post which I found quite helpful but for me it's only half the equation. In line with the following code, I need to take the string from a database, explode it into the 2d array, edit values in the array and implode it back ready for storage in the same format. So specifically backwards in the same order as the existing script.
The code from the other post >>
$data = "i love funny movies \n i love stackoverflow dot com \n i like rock song";
$data = explode(" \n ", $data);
$out = array();
$step = 0;
$last = count($data);
$last--;
foreach($data as $key=>$item){
foreach(explode(' ',$item) as $value){
$out[$key][$step++] = $value;
}
if ($key!=$last){
$out[$key][$step++] = ' '; // not inserting last "space"
}
}
print '<pre>';
print_r($out);
print '</pre>';

The quoted code inserts separate array elements which just have a space as value. One can wonder what benefit those bring.
Here are two functions you could use:
function explode2D($row_delim, $col_delim, $str) {
return array_map(function ($line) use ($col_delim) {
return explode($col_delim, $line);
}, explode($row_delim, $str));
}
function implode2D($row_delim, $col_delim, $arr) {
return implode($row_delim,
array_map(function ($row) use ($col_delim) {
return implode($col_delim, $row);
}, $arr));
}
They are each other's opposite, and work much like the standard explode and implode functions, except that you need to specify two delimiters: one to delimit the rows, and another for the columns.
Here is how you would use it:
$data = "i love funny movies \n i love stackoverflow dot com \n i like rock song";
$arr = explode2D(" \n ", " ", $data);
// manipulate data
// ...
$arr[0][2] = "scary";
$arr[2][2] = "balad";
// convert back
$str = implode2D(" \n ", " ", $arr);
See it run on repl.it.

Related

PHP get words with length longer than 3 from string

Is there a function that can cut words from a string that are small length e.g. "the, and, you, me, or" all these short words that are common in all sentences. i want to use this function to fill a fulltext search with criteria
before the method:
$fulltext = "there is ongoing work on creating a formal PHP specification.";
outcome:
$fulltext_method_solution = "there ongoing work creating formal specification."
$fulltext = "there is ongoing work on creating a formal PHP specification.";
$words = array_filter(explode(' ', $fulltext), function($val){
return strlen($val) > 3; // filter words having length > 3 in array
});
$fulltext_method_solution = implode(' ', $words); // join words into sentence
try this:
$fulltext = "there is ongoing work on creating a formal PHP specification.";
$result=array();
$array=explode(" ",$fulltext);
foreach($array as $key=>$val){
if(strlen($val) >3)
$result[]=$val;
}
$res=implode(" ",$result);
You can simply use implode, explode along with array_filter
echo implode(' ',array_filter(explode(' ',$fulltext),function($v){ return strlen($v) > 3;}));
or simply use preg_replace as
echo preg_replace('/\b[a-z]{1,3}\b/i','',$fulltext);
try this:
$stringArray = explode(" ", $fulltext);
foreach ($stringArray as $value)
{
if(strlen($value) < 3)
$fulltext= str_replace(" ".$value." " ," ",$fulltext);
}
Here is a working DEMO
Simply explode the string and check for the strlen()
$fulltext = "there is ongoing work on creating a formal PHP specification.";
$ex = explode(' ',$fulltext);
$res = '';
foreach ($ex as $txt) {
if (strlen($txt) > 3) {
$res .= $txt . ' ';
}
}
echo $res;
By using preg_replace
echo $string = preg_replace(array('/\b\w{1,3}\b/','/\s+/'),array('',' '),$fulltext);
This will also produce the desired results:
<?php
$fulltext = "there is ongoing work on creating a formal PHP specification.";
$fulltext = preg_replace('/(\b.{1,3}\s)/',' ',$fulltext);
echo $fulltext;
?>

In comma delimited string is it possible to say "exists" in php

In a comma delimited string, in php, as such: "1,2,3,4,4,4,5" is it possible to say:
if(!/*4 is in string bla*/){
// add it via the .=
}else{
// do something
}
In arrays you can do in_array(); but this isn't a set of arrays and I don't want to have to convert it to an array ....
Try exploding it into an array before searching:
$str = "1,2,3,4,4,4,5";
$exploded = explode(",", $str);
if(in_array($number, $exploded)){
echo 'In array!';
}
You can also replace numbers and modify the array before "sticking it back together" with implode:
$strAgain = implode(",", $exploded);
You could do this with regex:
$re = '/(^|,)' + preg_quote($your_number) + '(,|$)/';
if(preg_match($re, $your_string)) {
// ...
}
But that's not exactly the clearest of code; someone else (or even yourself, months later) who had to maintain the code would probably not appreciate having something that's hard to follow. Having it actually be an array would be clearer and more maintainable:
$values = explode(',', $your_string);
if(in_array((str)$number, $values)) {
// ...
}
If you need to turn the array into a string again, you can always use implode():
$new_string = implode(',', $values);

Sort the contents of the textfile in ascending

I am trying to develop a code that will sort the contents of the text file in ascending order. I have read the contents of the file and was able to display the texts.
I am having difficulty sorting them out in from low to high order, word by word.
I have tried the asort from php.net, but just could not get the code to work well.
thanks.
To answer your second question, you can read the text file into into a variable (like you've said you have already), eg. $variable, then use explode (http://php.net/manual/en/function.explode.php) to separate, at each space, each word into an array:
//$variable is the content from your text file
$output = explode(" ",$variable); //explode the content at each space
//loop through the resulting array and output
for ($counter=0; $counter < count($output); $counter++) {
echo $output[$counter] . "<br/>"; //output screen with a line break after each
} //end for loop
If your paragraph contains commas etc which you don't want to output you can replace those in the variable before exploding it.
//Split file by newlines "\n" into an array using explode()
$file = explode("\n",file_get_contents('foo.txt'));
//sort array with sort()
sort($file);
//Build string and display sorted contents.
echo implode("\n<br />",$file);
Sort functions needs to have an array as argument, make sure your file is in an array. asort is for associative arrays, so unless you need to keep the array keys you can use sort instead.
$file = "Hello world\ngoodbye.";
$words = preg_split("/\s+/", $file);
$clean_words = preg_replace("/[[:punct:]]+/", "", $words);
foreach ($clean_words as $key => $val) {
echo "words[" . $key . "] = " . $val . "\n";
}
--output:--
words[0] = Hello
words[1] = world
words[2] = goodbye
sort($clean_words, SORT_STRING | SORT_FLAG_CASE);
foreach ($clean_words as $key => $val) {
echo "words[" . $key . "] = " . $val . "\n";
}
--output:--
words[0] = goodbye
words[1] = Hello
words[2] = world
Try this
<?php
$filecontent = file_get_contents('exemple.txt');
$words = preg_split('/[\s,.;":!()?\'\-\[\]]+/', $filecontent, -1, PREG_SPLIT_NO_EMPTY);
$array_lowercase = array_map('strtolower', $words);
array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $words);
foreach($words as $value)
{
echo "$value <br>";
}
?>

preg_replace php to replace repeated characters

So I have a list of values like that goes like this:
values: n,b,f,d,e,b,f,ff`
I want to use preg_replace() in order to remove the repeated characters from the list of values (it will be inserted to a MySQL table). b and f are repeated. ff should not count as f because it's a different value. I know that \b \b will be used for that. I am not sure on how to take out the repeated b and f values as well as the , that precedes each value.
If the list is in a string looking like the example above, a regex is overkill. This does it just as well;
$value = implode(',', array_unique(explode(',', $value)));
I agree with other commenters that preg_replace is not the way to go; but, since you ask, you can write:
$str = preg_replace('/\b(\w+),(?=.*\b\1\b)/', '', $str);
That will remove all but the last instance of a given list-element.
No need for regex for this:
join(",", array_unique(split(",", $values)))
If this list you're dealing with is a simple string, a possible solution would be like this:
function removeDuplicates($str) {
$arr = explode(',', $str);
$arr = array_unique($arr);
return implode(',', $arr);
}
$values = removeDuplicates('n,b,f,d,e,b,f,ff'); // n,b,f,d,e,ff
$str = "values: n,b,f,d,e,b,f,ff";
$arr = array();
preg_match("/(values: )([a-z,]+)/i", $str, $match);
$values = explode(",", $match[2]);
foreach($values AS $value){
if(!$arr[$value]) $arr[$value] = true;
}
$return = $match[1];
foreach($arr AS $a){
$return .= ($i++ >= 1 ? "," : "").$a;
}

How line break content become one line paragraph?

*strong text*what i want to do is from my breakline content to one line paragraph
example my var_dump result:
string(212) "(73857,"2012-02-02 03:18:44","TXT",60143836234);"
string(122) "(73858,"2012-02-02 03:20:08","WAP",60143836234);"
string(211) "(73859,"2012-02-02 08:21:47","TXT",60163348563,);"
What i want to become:
string(555) "(73857,"2012-02-02 03:18:44","TXT",60143836234);(73858,"2012-02-02 03:20:08","WAP",60143836234);(73859,"2012-02-02 08:21:47","TXT",60163348563,);"
update (here is my code, $i is the line break records, if I able to make the breakline to one line, i will put in a new file )
foreach($get_line_feed_content as $i) {
$add_special_char = "(".$i.");";
var_dump($add_special_char);
if(!empty($i)){
$stringData = $final_content;
fwrite($save, $stringData);
fclose($save);
}
}
any idea?
Thank and highly appreciated your answer
Did you just want to glue the strings together? I don't see any line breaks from your dumps.
If that's the case, just do:
$finalString = $string1 . $string2 . $string3;
var_dump($finalString); //Strings should be glued as one.
If, however, each line is represented as an element in an array:
$stringsArray = array('string1', 'string2', 'string3');
$finalString = implode("", $stringsArray);
var_dump($finalString);
With your most recent update, this is what I would do:
$newString = '';
foreach($get_line_feed_content as $i) {
$newString .= "(".$i.");"; //concatenate
var_dump($newString); //You will get a lot of dumps and with each dump, a new string should be appended to it.
if(!empty($i)){
fwrite($save, $newString);
fclose($save);
}
}
if you want to glue strings you can do like this:
$data = $string1.$string2.$string3;
If you have array of strings do like this:
$strings = array('text1','text2','text3');
$data = implode('', $strings);

Categories