Created
February 13, 2022 00:12
-
-
Save sergioatanacio/8235fc5270c468be91e3315f4830ec2c to your computer and use it in GitHub Desktop.
He creado una función que a partir de unos caracteres, puede reconocer estos en un texto.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $token_stop_character = [ | |
| '(' => 'open_parentesis', | |
| ')' => 'close_parentesis', | |
| '=' => 'igual', | |
| '[' => 'open_corchete_cuadrado', | |
| ']' => 'close_corchete_cuadrado', | |
| ' ' => 'espacio', | |
| '*' => 'multiplicación', | |
| ',' => 'coma', | |
| ';' => 'punto_y_coma', | |
| ]; | |
| $multi_character_token = [ | |
| 'let' => 'creacion_variable', | |
| 'const' => 'creacion_constante', | |
| 'function' => 'creacion_funcion', | |
| '==' => 'comparación', | |
| '**' => 'potenciacion', | |
| ]; | |
| $tokens = array_merge($token_stop_character, $multi_character_token); | |
| $string = 'let hola = (uno) => [ uno ** 2, 5];'; | |
| $recurtion = function($stringFn, $iterator = 0, $previous_character = null, $token_index = 0, array $resulting_array = []) | |
| use (&$recurtion, $tokens, $token_stop_character, $multi_character_token) | |
| { | |
| $string_in_iterator = $stringFn[$iterator] ?? null; | |
| $string_to_parse = isset($previous_character) | |
| ? ($previous_character . $string_in_iterator) | |
| : $string_in_iterator; | |
| $there_is_a_token = isset($tokens[$string_to_parse]) || !isset($string_in_iterator) || isset($token_stop_character[$stringFn[$iterator + 1]]); | |
| $capturing_token = ($there_is_a_token) | |
| ? array_merge($resulting_array, [$token_index => | |
| [ | |
| 'token' => $string_to_parse, | |
| 'type' => $tokens[$string_to_parse] ?? 'variable', | |
| ] | |
| ]) | |
| : $resulting_array; | |
| $new_previous_character = ($there_is_a_token) | |
| ? null | |
| : $string_to_parse; | |
| $new_token_index = ($there_is_a_token) | |
| ? $token_index + 1 | |
| : $token_index; | |
| return !isset($string_in_iterator) | |
| ? $resulting_array | |
| : $recurtion($stringFn, $iterator + 1, $new_previous_character, $new_token_index, $capturing_token); | |
| }; | |
| var_dump($recurtion($string)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment