PHP: Tokenizing input string for command-line website - php

I am working on a small side-project that involves building a command-line/terminal-like interface. I've chosen to use Symfony's Console component as the backbone for the main functionality.
What's troubling me is how to handle the various forms of input the user can give.
Here's an example:
Let's say I'd like to create a MessageCommand that take's both arguments as well as options (option names are prefixed with --). This command should have the functionality to read and send a message to another user. To send a message, the user should be able to enter this, without quotes, like so:
message send --title Hello there --text How are you doing?
So, this is the code I'm trying to get to work for the example above:
private function tokenize($input)
{
$tokens = array();
$isOption = false;
$len = strlen($input);
$previous = '';
$buffer = '';
for ($i = 0; $i < $len; $i++)
{
$current = $input[$i];
switch ($current)
{
case '-';
if ($previous == '-')
{
$isOption = true;
}
$buffer .= '-';
break;
default:
if ($isOption || $current != ' ')
{
$buffer .= $current;
}
elseif ($current == " " && $previous != " " && strlen($buffer) > 0)
{
$tokens[] = $buffer;
$buffer = "";
}
}
$previous = $current;
}
if (strlen($buffer) > 0)
{
$tokens[] = $buffer;
}
return $tokens;
}
.. which, in it's current state, tokenizes said string into:
array(
'message',
'send',
'--title Hello there --text How are you doing?'
)
So, I am asking you for help as to how I should modify above code, so that it would give an array like this instead:
array(
'message',
'send',
'--title',
'Hello there',
'--text',
'How are you doing?'
)
Thank you so much in advance!

I would explode your input with space, and then in a loop and check if substr( $string_n, 0, 2 ) === "--", then concatenate all the next rows untill i find again this "--".
$input = 'message send --title Hello there --text How are you doing?';
$rows = explode(' ', $input);
$tokens = array();
$isOption = false;
foreach ($rows as $row) {
if(substr($row, 0, 2) === '--') {
$isOption = true;
$tokens[] = $row;
} else if($isOption === true && substr($tokens[count($tokens) - 1], 0, 2) !== '--') {
$tokens[count($tokens) - 1] .= ' ' . $row;
} else {
$tokens[] = $row;
}
}
var_dump($tokens);
what i get in the var_dump :
array(6) {
[0]=>
string(7) "message"
[1]=>
string(4) "send"
[2]=>
string(7) "--title"
[3]=>
string(11) "Hello there"
[4]=>
string(6) "--text"
[5]=>
string(18) "How are you doing?"
}

Related

Movie Trailer Page views with Sessions PHP

Here is my problem..
I have Session with Array looking like this
array(3) { [0]=> array(1) { ["trailer"]=> array(1) { ["id"]=> string(5) "id-10" } } [1]=> array(1) { ["trailer"]=> array(1) { ["id"]=> string(5) "id-11" } } [2]=> array(1) { ["trailer"]=> array(1) { ["id"]=> string(5) "id-10" } } }
and an php method .. oh and 1 more thing, im using laravel 5.6
My Code:
public function updateTrailerViews($id = 1){
$trailerViews = array(array());
$trailerViewsCount = \Session::get('trailerViews') == NULL ? 1 : count(\Session::get('trailerViews'));
if($trailer['id'] == NULL){
$id = 1;
}
if (\Session::get('trailerViews') == NULL) {
for ($i=0; $i < $trailerViewsCount; $i++) {
$trailerViews[$i]['trailer']['id'] = 'id-'.$id;
//$trailer['views'] = $trailer['views']+1;
//$trailer->save();
}
\Session::put('trailerViews', $trailerViews);
}else{
for($i=0;$i<$trailerViewsCount;$i++){
if(\Session::get('trailerViews')[$i]['trailer']['id'] != 'id-'.$id){
$idNotExist = 'true';
}else{
$idNotExist = 'false';
}
}
if($idNotExist == 'true'){
$trailerViewsCount1 = $trailerViewsCount+1;
for($int=0;$int<$trailerViewsCount1;$int++){
if($int == $trailerViewsCount1-1){
// if is the last integer of the loop add the new record
$trailerViews[$int]['trailer']['id'] = 'id-'.$id;
}else{
for($int1 = 0; $int1 < $trailerViewsCount; $int1++){
// if the integer is not the last number of the loop add the previous records from the session
$trailerID = \Session::get('trailerViews')[$int1]['trailer']['id'];
$trailerViews[$int1]['trailer']['id'] = $trailerID;
}
}
\Session::put('trailerViews', $trailerViews);
}
}
}
$trailerViewsCountReturn = count(\Session::get('trailerViews'));
//$trailerViewsNumber = \AppHelper::instance()->short_number_format($trailer['views']);
return var_dump(\Session::get('trailerViews'));
}
The problem is when im trying to check the unique id of the page sometimes have a bug, when open page with id=2 then id=5 or other.. and again open id=2 the id is going to be added again.
I wanna make it with unique page id's only.
SOLVED!
public function updateTrailerViews($id = 1){
$trailer = Trailers::find($id);
$trailerViews = array(array());
$trailerViewsCount = \Session::get('trailerViews') == NULL ? 1 : count(\Session::get('trailerViews'));
if($trailer['id'] == NULL){
$id = 1;
}
if (\Session::get('trailerViews') == NULL) {
for ($i=0; $i < $trailerViewsCount; $i++) {
$trailerViews[$i] = 'id-'.$id;
$trailer['views'] = $trailer['views']+1;
$trailer->save();
}
\Session::put('trailerViews', $trailerViews);
}else{
if(!in_array('id-'.$id, \Session::get('trailerViews'))){
if($trailer['id'] == $id){
$idNotExist = 'true';
$trailer['views'] = $trailer['views']+1;
$trailer->save();
}else{
$idNotExist = 'false';
}
}else{
$idNotExist = 'false';
}
if($idNotExist == 'true'){
$trailerViewsCount1 = $trailerViewsCount+1;
for($int=0;$int<$trailerViewsCount1;$int++){
if($int == $trailerViewsCount1-1){
// if is the last integer of the loop add the new record
$trailerViews[$int] = 'id-'.$id;
}else{
for($int1 = 0; $int1 < $trailerViewsCount; $int1++){
// if the integer is not the last number of the loop add the previous records from the session
$trailerID = \Session::get('trailerViews')[$int1];
$trailerViews[$int1] = $trailerID;
}
}
$trailerViews = array_unique($trailerViews);
\Session::put('trailerViews', $trailerViews);
}
}
}
$trailerViewsCountReturn = count(\Session::get('trailerViews'));
$trailerViewsNumber = \AppHelper::instance()->short_number_format($trailer['views']);
return $trailerViewsNumber;
}

Creating array from another array php

I have some array that look like this
$links =array('proizvodi','pokloni', 'kuhinja');
I need to create another array that will look like this
$linksNew =array('proizvodi/','proizvodi/pokloni/', 'proizvodi/pokloni/kuhinja/');
Txanks in advance
This would be a primitive approach:
<?php
$input = ['proizvodi','pokloni', 'kuhinja'];
$output = [];
$previous = '';
foreach ($input as $entry) {
$output[] = $previous . $entry . '/';
$previous = end($output);
}
var_dump($output);
This is a version some might consider a bit more elegant:
<?php
$input = ['proizvodi','pokloni', 'kuhinja'];
$output = [];
$previous = '';
array_walk($input, function($entry) use (&$previous, &$output) {
$output[] = $previous . $entry . '/';
$previous = end($output);
});
var_dump($output);
The output of both versions obviously is:
array(3) {
[0]=>
string(10) "proizvodi/"
[1]=>
string(18) "proizvodi/pokloni/"
[2]=>
string(26) "proizvodi/pokloni/kuhinja/"
}
This would be a approach without a for or foreach loop
$links = array('proizvodi','pokloni', 'kuhinja');
$newLinks = array_map(function($i) use ($links) {
return implode(array_slice($links, 0, $i), '/') . '/';
}, range(1, count($links)));
Trying to think of a slicker way, but this works:
for($i=0; $i<count($links); $i++) {
$linksNew[] = implode('/', array_slice($links, $i)) . '/';
}
$linksNew = array_reverse($linksNew);

How can I turn a value of an array into the key of an array?

I am parsing a text file that looks more or less like this:
123.animal=cat
123.name=fred
123.food=fish
345.animal=dog
petshop=zoonoria
This is how I am parsing it:
$file_path = $filename;
$linesArray = file($file_path);
$properties = array();
foreach ($linesArray AS $line) {
if (strlen($line) && $line[0] == '#') {
$pdate = substr($line, 1);
$date = rtrim($pdate);
$formatted = DateTime::createFromFormat('* M d H:i:s T Y',$date);
}
if (false !== ($pos = strpos($line, '='))) {
$prop=array();
$prop[trim(substr($line, 0, $pos))] = trim(substr($line, $pos + 1));
$lineContArray = explode("=", $line);
$identArray = explode(".", $lineContArray[0]);
$ident = $identArray[0];
$type = $identArray[1];
$value = trim($lineContArray[1]);
$found = 0;
for ($i=0; $i<count($properties); $i++) {
if ($properties['number'] == $ident) {
$properties[$i][$type]= $value;
$found=1;
break;
}
}
if ($found == 0) {
if (!empty($type)) {
$properties[] = array('number' => $ident, $type => $value);
} else {
$properties[] = array($ident => $value); }
}
}
My result is:
array(3) {
[0]=>
array(2) {
["number"]=>
string(3) "123"
["animal"]=>
string(3) "cat"
}
[1]=>
array(2) {
["number"]=>
string(3) "123"
["name"]=>
string(4) "fred"
}
[3]=>
array(2) {
["number"]=>
string(3) "345"
["animal"]=>
string(4) "dog"
}
[4]=>
array(1) {
["petshop"]=>
string(5) "zoonoria"
}
}
But I need the array to be different, this is the result I like to achieve:
array(3) {
[123]=>
array(3) {
["animal"]=>
string(3) "cat"
["name"]=>
string(4) "fred"
["food"]=>
string(4) "fish"
}
[345]=>
array(1) {
["animal"]=>
string(3) "dog"
}
[petshop]=>
string(8) "zoonoria"
}
}
So my main problem is, I do not know how to turn number into the key. I tried various things, but I failed. I am really happy for every hint.
I tried the solution of Svetlio:
$file_path = $filename;
$linesArray = file($file_path);
$properties = array();
foreach ( $linesArray as $str) {
$exp = explode ('=', $str);
if(count($exp) == 2){
$exp2 = explode('.', $exp[0]);
if( count($exp2) == 2 ) {
$properties [$exp2[0]][$exp2[1]] = $exp[1];
} else {
$properties [$exp[0]] = $exp[1];
}
} else {
}
}
My result:
array(3) {
["123"]=>
array(3) {
["animal"]=>
string(3) "cat
"
["name"]=>
string(4) "fred
"
["food"]=>
string(4) "fish
"
}
[345]=>
array(1) {
["animal"]=>
string(3) "dog
"
}
["petshop"]=>
string(3) "zoonoria
"
}
Here is working solution but it doesn't cover the cases where stings don't contain = or have more than 1 of them..
$strings = array(
'123.animal=cat',
'123.name=fred',
'123.food=fish',
'345.animal=dog',
'petshop=zoonoria'
);
$array = array();
foreach ( $strings as $str) {
// I accept that there is 1 = at strings possible
$exp = explode ('=', $str);
if(count($exp) == 2){
$exp2 = explode('.', $exp[0]);
if( count($exp2) == 2 ) {
$array[$exp2[0]][$exp2[1]] = $exp[1];
} else {
// if there are multiple/null dots i set the string as key
$array[$exp[0]] = $exp[1];
}
} else {
// what to do if there are no or many = = = in the string ?
}
}
var_dump($array);
After getting the result you can use array_reduce to get the desired result
$result = array_reduce($initialArray, function ($result, $item) {
$number = isset($item['number']) ? $item['number'] : end(array_keys($result));
if (!isset($result[$number])) {
$result[$number] = array();
}
foreach ($item as $key => $value) {
if ($key == 'number') continue;
$result[$number][$key] = $value;
}
return $result;
}, array());
foreach ($linesArray AS $line) {
if (strlen($line) && $line[0] == '#') {
$pdate = substr($line, 1);
$date = rtrim($pdate);
$formatted = DateTime::createFromFormat('* M d H:i:s T Y',$date);
}
if (false !== ($pos = strpos($line, '='))) {
$prop=array();
$prop[trim(substr($line, 0, $pos))] = trim(substr($line, $pos + 1));
$lineContArray = explode("=", $line);
$identArray = explode(".", $lineContArray[0]);
$ident = $identArray[0];
$type = $identArray[1];
$value = trim($lineContArray[1]);
$found = 0;
for ($i=0; $i<count($properties); $i++) {
if ($properties['number'] == $ident) {
$properties[$i][$type]= $value;
$found=1;
break;
}
}
if ($found) {
if ($type && $ident) {
$properties[$ident][$type] = $value;
} else if (!$type && $ident) {
$properties[$ident][] = $value;
}else if ($type && !$ident){
$properties[$type][] = $value;
}
}
$data = '123.animal=cat
123.name=fred
123.food=fish
345.animal=dog
petshop=zoonoria';
$ini = parse_ini_string($data);
$result = [];
foreach ($ini as $key => $value) {
$splitKey = explode('.', $key);
$iniPtr = &$result;
foreach($splitKey as $subKey) {
if (!isset($iniPtr[$subKey])) { $iniPtr[$subKey] = null; }
$iniPtr = &$iniPtr[$subKey];
}
$iniPtr = $value;
}
unset($iniPtr);
var_dump($result);
Demo
In your case, use $ini = parse_ini_file($file_path); to read your file data into $ini

PHP String array to Tree Structure

I have String array like below format
Array(
"Courses",
"Courses/PHP",
"Courses/PHP/Array",
"Courses/PHP/Functions",
"Courses/JAVA",
"Courses/JAVA/String");
I need result like below
Courses
- PHP
- Array
- Functions
- JAVA
- Strings
I used substr option to get result.
for($i=0;$i<count($outArray);$i++)
{
$strp = strrpos($outArray[$i], '/')+1;
$result[] = substr($outArray[$i], $strp);
}
But I didn't get result like tree structure.
How do I get result like tree structure.
Something like that?
$a = array(
"Courses",
"Courses/PHP",
"Courses/PHP/Array",
"Courses/PHP/Functions",
"Courses/JAVA",
"Courses/JAVA/String");
$result = array();
foreach($a as $item){
$itemparts = explode("/", $item);
$last = &$result;
for($i=0; $i < count($itemparts); $i++){
$part = $itemparts[$i];
if($i+1 < count($itemparts))
$last = &$last[$part];
else
$last[$part] = array();
}
}
var_dump($result);
The result is:
array(1) {
["Courses"]=>
array(2) {
["PHP"]=>
array(2) {
["Array"]=>
array(0) {
}
["Functions"]=>
array(0) {
}
}
["JAVA"]=>
&array(1) {
["String"]=>
array(0) {
}
}
}
}
How about this one:
<?php
$outArray = Array(
"Courses",
"Courses/PHP",
"Courses/PHP/Array",
"Courses/PHP/Functions",
"Courses/JAVA",
"Courses/JAVA/String");
echo "-" . $outArray[0] . "<br/>";
for($i=0;$i<count($outArray) - 1;$i++)
{
create_tree($outArray[$i],$outArray[$i+1]);
}
function create_tree($prev, $arr)
{
$path1 = explode("/", $prev);
$path2 = explode("/", $arr);
if (count($path1) > count($path2))
echo str_repeat(" ",count($path1) - 1) . "-" . end($path2);
else
echo str_repeat(" ",count($path2) - 1) . "-" . end($path2);
echo $outArray[$i] . "<br/>";
}
Outputs:
-Courses
-PHP
-Array
-Functions
-JAVA
-Strings

explode text but returning each array piece as three words

I'm getting troubles on a simple php function!
What i want to do is:
$text = "this is my data content with many words on it";
I want to write a function that turns the variable string $text as an array like this:
$array = array("this is my", "data content with", "many words on", "it");
In other words, each array piece should have 3 words on it!
This should work:
function split3($text)
{
$array = array();
foreach(explode(' ',$text) as $i=>$word)
{
if($i%3) {
$array[floor($i/3)] .= ' '.$word;
} else {
$array[$i/3] = $word;
}
}
return $array;
}
$text = "this is my data content with many words on it";
var_dump(split3($text));
returns:
array(4) {
[0]=>
string(10) "this is my"
[1]=>
string(17) "data content with"
[2]=>
string(13) "many words on"
[3]=>
string(2) "it"
}
You can do this quite easily with just the one regex. There should be no need for a loop here.
function splitWords($text, $noOfWords = 3) {
$res = array();
preg_match_all('/(\w+\s*){1,'.$noOfWords.'}/', $text, $res);
return $res[0];
}
var_dump(splitWords('one one one two two two thre thre thre four four'));
Result :
array(4) {
[0]=>
string(12) "one one one "
[1]=>
string(12) "two two two "
[2]=>
string(15) "thre thre thre "
[3]=>
string(9) "four four"
}
The basic regex is just
/(\w\s*){1,3}/
if you dont want to catch the remaining 1 or 2 word runs you could just change the count to {3}.
Taken from http://php.net/manual/en/function.preg-split.php:
<?php
/**
* Split a string into groups of words with a line no longer than $max
* characters.
*
* #param string $string
* #param integer $max
* #return array
**/
function split_words($string, $max = 1)
{
$words = preg_split('/\s/', $string);
$lines = array();
$line = '';
foreach ($words as $k => $word) {
$length = strlen($line . ' ' . $word);
if ($length <= $max) {
$line .= ' ' . $word;
} else if ($length > $max) {
if (!empty($line)) $lines[] = trim($line);
$line = $word;
} else {
$lines[] = trim($line) . ' ' . $word;
$line = '';
}
}
$lines[] = ($line = trim($line)) ? $line : $word;
return $lines;
}
?>
There are loads of ways you can do it - this option is probably not the quickest. Are you using this piece of code a lot or not?
how about
<?php
print_r(split3('this is my data content with many words on it'));
function split3($text){
$tmp = explode(" ", $text);
$res = array();
for($i = 0; $i < count($tmp); $i+=3){
$tmpRes = array();
if(isset($tmp[$i])){ $tmpRes[] = $tmp[$i]; }
if(isset($tmp[$i+1])){ $tmpRes[] = $tmp[$i+1]; }
if(isset($tmp[$i+2])){ $tmpRes[] = $tmp[$i+2]; }
$res[] = implode(" ", $tmpRes);
}
return $res;
}
?>
The other answers seem overly verbose. Here's some slightly more idiomatic PHP to do it, and as an added bonus the number of words per chunk is a parameter.
function create_word_chunks($text, $num_words) {
$words = explode(' ', $text);
$start = 0;
$word_chunks = array();
while ($start < count($words)) {
$word_chunks[] = implode(' ', array_slice($words, $start, $num_words));
$start += $num_words;
}
return $word_chunks;
}
$text = "this is my data content with many words on it";
var_dump(create_word_chunks($text, 3));
There should be a way of doing this without regular expressions. Try this:
<?php
//Second argument makes the function return an array of words
$words = str_word_count($text, 1);
foreach(array_chunk($words, 3) as $array){
$pieces[] = implode(' ', $array);
}
?>
$pieces will be an array, each member of which will contain a string with the words. The last member may be shorter than three words depending on the number of words in the original string.

Categories