How to parse console command strings in PHP with quotes - php

For my game I'm coding a console that sends messages via AJAX and then receives output from the server.
For example, an input would be:
/testmessage Hello!
However, I would also need to parse the quotes e.g.:
/testmessage "Hello World!"
However, since I am simply exploding the string with spaces, PHP sees "Hello and World!" as separate parameters. How do I make PHP think that "Hello World!" is one parameter?
Right now I'm using the following code to parse the command:
// Suppose $inputstring = '/testmessage "Hello World!"';
$inputstring = substr($inputstring, 1);
$parameters = explode(" ", $inputstring);
$command = strtolower($parameters[0]);
switch ($command) {
case "testmessage":
ConsoleDie($parameters[1]);
break;
}
Thank you in advance.

This code will do what you want:
$params = preg_split('/(".*?")/', '/testmessage "Hello World!" 1 2 3', -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$realParams = array();
foreach($params as $param)
{
$param = trim($param);
if ($param == '')
continue;
if (strpos($param, '"') === 0)
$realParams = array_merge($realParams, array(trim($param, '"')));
else
$realParams = array_merge($realParams, explode(' ', $param));
}
unset($params);
print_r($realParams);
that print:
array(5) {
[0]=>
string(12) "/testmessage"
[1]=>
string(14) "Hello World!"
[2]=>
string(1) "1"
[3]=>
string(1) "2"
[4]=>
string(1) "3"
}
Note: As you can see the first parameter is the command

Hope this code is more 'understandable'
$input = $inputstring = '/testmessage "Hello World!" "single phrase" level two';
// find the parameters surrounded with quotes, grab only the value (remove "s)
preg_match_all('/"(.*?)"/', $inputstring, $quotes);
// for each parameters with quotes, put a 'placeholder' like {{1}}, {{2}}
foreach ($quotes[1] as $key => $value) {
$inputstring = str_replace($value, "{{{$key}}}", $inputstring);
}
// then separate by space
$parameters = explode(" ", $inputstring);
// replace the placeholders {{1}} with the original value
foreach ($parameters as $key => $value) {
if (preg_match('{{(\d+)}}', $value, $matches)) {
$parameters[$key] = $quotes[1][$matches[1]];
}
}
// here you go
print_r($parameters);

I may not have understood you fully, but if you are assuming that the first word is always a command word, and anything following is 'one parameter' you could do the following
$inputstring = substr($inputstring, 1);
$parameters = explode(" ", $inputstring);
// shift the first element off the array i.e. the command
$command = strtolower(array_shift($parameters));
// Glue the rest of the array together
$input_message = implode($parameters);
switch ($command) {
case "testmessage":
ConsoleDie($input_message);
break;
}

You can use the Symfony Console Component which offers a secure and clean way to get console inputs.
For your use case you should do:
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputArgument;
$input = new ArgvInput(null, new InputDefinition(array(
new InputArgument('message', InputArgument::REQUIRED)
)));
$parameters = $input->getArguments(); // $parameters['message'] contains the first argument

Related

Parse BBCode in array

I am trying to call a function from BBCode(like WordPress shortcodes). but I didn't find any code to do that, only I found HTML tag parser like:
[bold]Bold text[/bold]
->
<b>Bold text</b>
But I want to save it as an array, for example:
[date format="j M, Y" type="jalali"]
to something like this:
array(
'date' => array(
'format' => 'j M, Y',
'type' => 'jalali'
)
)
*Edited
I made a code to do this (sorry if my English is bad):
[date format="Y/m/d" type="jalali"] =>
Step 1: Get code between "[" and "]":
date format="Y/m/d" type="jalali"
Step 2: Explode space in the code:
$code = array('date', 'format="Y/m/d"', 'type="jalali"')
Step 3: Get shortcode name(offset 0 of $code) and get
difference($code excluded offset 0):
$name = 'date'
$attr = array('format="Y/m/d"', 'type="jalali"')
Step 4: Now I have attributes and code name. But the problem is if
put space in attributes value it will explode that too:
[date format="j M, Y" type="jalali"] =>
$code = array('date', 'format="j', 'M,', ' Y"', 'type="jalali"');
Now how can I fix this or get name and attributes with regex or anything else?
You can try this using regex
$code = '[date format="j M, Y" type="jalali"]';
preg_match_all("/\[([^\]]*)\]/", $code, $matches);
$codes = [];
foreach($matches[1] as $match) {
// Normalize quotes into double quotes
$match = str_replace("'",'"',$match);
// Split by space but ignore inside of double quotes
preg_match_all('/(?:[^\s+"]+|"[^"]*")+/',$match,$tokens);
$parsed = [];
$prevToken = '';
foreach($tokens[0] as $token) {
if(strpos($token,'=') !== false) {
if($prevToken !== '') {
$parts = explode('=',$token);
$parsed[$prevToken][$parts[0]] = trim($parts[1],'"\'');
}
} else {
$parsed[$token] = [];
$prevToken = $token;
}
}
$codes[] = $parsed;
}
var_dump($codes);
Result:
array(1) {
[0]=>
array(1) {
["date"]=>
array(2) {
["format"]=>
string(6) "j M, Y"
["type"]=>
string(6) "jalali"
}
}
}

PHP: String to multidimensional array

(Sorry for my bad English)
I have a string that I want to split into an array.
The corner brackets are multiple nested arrays.
Escaped characters should be preserved.
This is a sample string:
$string = '[[["Hello, \"how\" are you?","Good!",,,123]],,"ok"]'
The result structure should look like this:
array (
0 =>
array (
0 =>
array (
0 => 'Hello, \"how\" are you?',
1 => 'Good!',
2 => '',
3 => '',
4 => '123',
),
),
1 => '',
2 => 'ok',
)
I have tested it with:
$pattern = '/[^"\\]*(?:\\.[^"\\]*)*/s';
$return = preg_match_all($pattern, $string, null);
But this did not work properly. I do not understand these RegEx patterns (I found this in another example on this page).
I do not know whether preg_match_all is the correct command.
I hope someone can help me.
Many Thanks!!!
This is a tough one for a regex - but there is a hack answer to your question (apologies in advance).
The string is almost a valid array literal but for the ,,s. You can match those pairs and then convert to ,''s with
/,(?=,)/
Then you can eval that string into the output array you are looking for.
For example:
// input
$str1 = '[[["Hello, \\"how\\" are you?","Good!",,,123]],,"ok"]';
// replace , followed by , with ,'' with a regex
$pattern = '/,(?=,)/';
$replace = ",''";
$str2 = preg_replace($pattern, $replace, $str1);
// eval updated string
$arr = eval("return $str2;");
var_dump($arr);
I get this:
array(3) {
[0]=>
array(1) {
[0]=>
array(5) {
[0]=>
string(21) "Hello, "how" are you?"
[1]=>
string(5) "Good!"
[2]=>
string(0) ""
[3]=>
string(0) ""
[4]=>
int(123)
}
}
[1]=>
string(0) ""
[2]=>
string(2) "ok"
}
Edit
Noting the inherent dangers of eval the better option is to use json_decode with the code above e.g.:
// input
$str1 = '[[["Hello, \\"how\\" are you?","Good!",,,123]],,"ok"]';
// replace , followed by , with ,'' with a regex
$pattern = '/,(?=,)/';
$replace = ',""';
$str2 = preg_replace($pattern, $replace, $str1);
// eval updated string
$arr = json_decode($str2);
var_dump($arr);
If you can edit the code that serializes the data then it's a better idea to let the serialization be handled using json_encode & json_decode. No need to reinvent the wheel on this one.
Nice cat btw.
You might want to use a lexer in combination with a recursive function that actually builds the structure.
For your purpose, the following tokens have been used:
\[ # opening bracket
\] # closing bracket
".+?(?<!\\)" # " to ", making sure it's not escaped
,(?!,) # a comma, not followed by a comma
\d+ # at least one digit
,(?=,) # a comma followed by a comma
The rest is programming logic, see a demo on ideone.com. Inspired by this post.
class Lexer {
protected static $_terminals = array(
'~^(\[)~' => "T_OPEN",
'~^(\])~' => "T_CLOSE",
'~^(".+?(?<!\\\\)")~' => "T_ITEM",
'~^(,)(?!,)~' => "T_SEPARATOR",
'~^(\d+)~' => "T_NUMBER",
'~^(,)(?=,)~' => "T_EMPTY"
);
public static function run($line) {
$tokens = array();
$offset = 0;
while($offset < strlen($line)) {
$result = static::_match($line, $offset);
if($result === false) {
throw new Exception("Unable to parse line " . ($line+1) . ".");
}
$tokens[] = $result;
$offset += strlen($result['match']);
}
return static::_generate($tokens);
}
protected static function _match($line, $offset) {
$string = substr($line, $offset);
foreach(static::$_terminals as $pattern => $name) {
if(preg_match($pattern, $string, $matches)) {
return array(
'match' => $matches[1],
'token' => $name
);
}
}
return false;
}
// a recursive function to actually build the structure
protected static function _generate($arr=array(), $idx=0) {
$output = array();
$current = 0;
for($i=$idx;$i<count($arr);$i++) {
$type = $arr[$i]["token"];
$element = $arr[$i]["match"];
switch ($type) {
case 'T_OPEN':
list($out, $index) = static::_generate($arr, $i+1);
$output[] = $out;
$i = $index;
break;
case 'T_CLOSE':
return array($output, $i);
break;
case 'T_ITEM':
case 'T_NUMBER':
$output[] = $element;
break;
case 'T_EMPTY':
$output[] = "";
break;
}
}
return $output;
}
}
$input = '[[["Hello, \"how\" are you?","Good!",,,123]],,"ok"]';
$items = Lexer::run($input);
print_r($items);
?>

Get the difference between two strings

I am creating a wildcard search/replace function and need to find the difference between two strings. I have tried some functions like array_diff and preg_match, browsed my way trough ~10 google pages with no solution.
I have a simple solution right now, but want to implement support for unknown value before wildcard
Here's what I got:
function wildcard_search($string, $wildcard) {
$wildcards = array();
$regex = "/( |_|-|\/|-|\.|,)/";
$split_string = preg_split($regex, $string);
$split_wildcard = preg_split($regex, $wildcard);
foreach($split_wildcard as $key => $value) {
if(isset($split_string[$key]) && $split_string[$key] != $value) {
$wildcards[] = $split_string[$key];
}
}
return $wildcards;
}
Example usage:
$str1 = "I prefer Microsoft products to Apple but love Linux"; //original string
$str2 = "I prefer * products to * but love *"; //wildcard search
$value = wildcard_search($str1, $str2);
//$value should now be array([0] => "Microsoft", [1] => "Apple", [2] => "Linux");
shuffle($value);
vprintf('I prefer %s products to %s but love %s', $value);
// now we can get all kinds of outputs like:
// I prefer Microsoft products to Linux but love Apple
// I prefer Apple products to Microsoft but love Linux
// I prefer Linux products to Apple but love Microsoft
// etc..
I want to implement support for unknown value before the wildcard.
Example:
$value = wildcard_search('Stackoverflow is an awesome site', 'Stack* is an awesome site');
// $value should now be array([0] => 'overflow');
// Because the wildcard (*) represents overflow in the second string
// (We already know some parts of the string but want to find the rest)
Could this be done without to much hassle with hundreds of loops etc.?
I'd change your function to use preg_quote and replace the escaped \* character with (.*?) instead:
function wildcard_search($string, $wildcard, $caseSensitive = false) {
$regex = '/^' . str_replace('\*', '(.*?)', preg_quote($wildcard)) . '$/' . (!$caseSensitive ? 'i' : '');
if (preg_match($regex, $string, $matches)) {
return array_slice($matches, 1); //Cut away the full string (position 0)
}
return false; //We didn't find anything
}
Example:
<?php
$str1 = "I prefer Microsoft products to Apple but love Linux"; //original string
$str2 = "I prefer * products to * but love *"; //wildcard search
var_dump( wildcard_search($str1, $str2) );
$str1 = 'Stackoverflow is an awesome site';
$str2 = 'Stack* is an awesome site';
var_dump( wildcard_search($str1, $str2) );
$str1 = 'Foo';
$str2 = 'bar';
var_dump( wildcard_search($str1, $str2) );
?>
Output:
array(3) {
[0]=>
string(9) "Microsoft"
[1]=>
string(5) "Apple"
[2]=>
string(5) "Linux"
}
array(1) {
[0]=>
string(8) "overflow"
}
bool(false)
DEMO

Parsing a string separated by semicolon

How can I parse this string
name:john;phone:12345;website:www.23.com;
into becoming like this
$name = "john";
$phone = "12345"
.....
because I want to save the parameter in one table column, I see joomla using this method to save the menu/article parameter.
Something like this(explode() is the way):
$string = 'name:john;phone:12345;website:www.23.com';
$array = explode(';',$string);
foreach($array as $a){
if(!empty($a)){
$variables = explode(':',$a);
$$variables[0] = $variables[1];
}
}
echo $name;
Working example
Please note: String must be like this, variable_name:value;variable_name2:value and the variable_name or variable cant contain ; or :
Here's how I'd do it:
Use explode() and split the string with ; as the delimiter.
Loop through the result array and explode() by :
Store the second part in a variable and push it into the result array
Optionally, if you want to convert the result array back into a string, you can use implode()
Code:
$str = 'name:john;phone:12345;website:www.23.com;';
$parts = explode(';', $str);
foreach ($parts as $part) {
if(isset($part) && $part != '') {
list($item, $value) = explode(':', $part);
$result[] = $value;
}
}
Output:
Array
(
[0] => john
[1] => 12345
[2] => www.23.com
)
Now, to get these values into variables, you can simply do:
$name = $result[0];
$phone = $result[1];
$website = $result[2];
Demo!
Use explode()
explode — Split a string by string
Description
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.
<?php
$string = "name:john;phone:12345;website:www.23.com;";
$pieces = explode(";", $string);
var_dump($pieces);
?>
Output
array(4) {
[0]=>
string(9) "name:john"
[1]=>
string(11) "phone:12345"
[2]=>
string(18) "website:www.23.com"
[3]=>
string(0) ""
}
DEMO
try this
<?php
$str = "name:john;phone:12345;website:www.23.com";
$array=explode(";",$str);
if(count($array)!=0)
{
foreach($array as $value)
{
$data=explode(":",$value);
echo $data[0]." = ".$data[1];
echo "<br>";
}
}
?>

Fron Array (var_dump) to my array?

I Make a
echo '<pre>';
echo var_dump($arrayX);
echo '</pre>'
I got the result:
array(6) {
[0]=>
string(9) "AAA"
[1]=>
string(13) "BBB"
[2]=>
string(8) "CCC"
[3]=>
string(8) "DDD"
[4]=>
string(8) "EEE"
[5]=>
string(13) "FFF"
}
How Can I make It to A New array
What I want is to get arrayX in this format :
array('AAA', 'BBB' , 'CCC','DDD', 'EEE', 'FFF');
$myarray = array('AAA', 'BBB' , 'CCC','DDD', 'EEE', 'FFF');
If you want a copy of it then
$a = $arrayX;
However if you have to convert it to some string format then the better way of doing it would be this
$dump = var_export($a,true);
eval('$b = ' . $dump . ';');
Or better yet
$s = serialize($a);
$c = unserialize($s);
If that does not do it then here is how to parse the vardump format in question
function parseValue($value) {
return substr(preg_replace('/\s*[a-z]+\([0-9]+\)\s+"(.*)/','\\1',$value),0,-2);
}
function parseIndex($index) {
return preg_replace('/[^[]*\[([0-9]+)\].*/','\\1',$index);
}
function parseVardump($dump) {
$lines = explode("\n",$dump);
foreach ($lines as $line) {
switch (true) {
case preg_match('/array\([0-9]+\) {/',$line) :
break;
case preg_match('/\[[0-9]+\]=>/',$line) :
// end previous value
if (isset($index)) {
$ar[$index] = parseValue($value);
}
$index = parseIndex($line);
$value = '';
break;
case preg_match('/}$/',$line) :
if (isset($index)) {
$ar[$index] = parseValue($value);
}
break;
default:
$value .= $line . "\n";
break;
}
}
return $ar;
}
$a = array("AAA\n", 'BBB' , 'CCC','DDD', 'EEE', 'FFF');
ob_start();
var_dump($a);
$dump = ob_get_contents();
ob_end_clean();
$ar = parseVardump($dump);
ehm, …? this:
$myarray = $arrayX;
if you want to make it complicated, you could use var_export
I must admit I don't understand your question.
If you want a copy of $arrayX, then simply type
$myarray = $arrayX;
you could right a simple function to output as the format you wish. like this one:
<?php
function dump_array($ar) {
$output = 'array(';
$lastIndex = count($ar) - 1;
$counter = 0;
foreach($ar as $key => $value) {
$output .= (is_string($value) ? "'{$value}'" : $value) . ( $counter++ < $lastIndex ? ', ' : '' );
}
$output .= ')';
return $output;
}
?>
although remember that the built-in "var_dump()" function recurses into arrays and shows information about objects inside the array. if you need such functionality, you should extend this function to do so.
If I understand it, what you are doing is outputing your array on some website and trying to create it again on another site which fetch the first one.
If this is right and you have control over the first site (the one doing the print_r), I think you should use the serialize and unserialize functions.

Categories