How to use the PHP preg_match command

0

How do I use preg_match to detect a string where it has to start with "/ command"?

This function, for me, is very complicated to understand ...

I wanted to detect a / command at the beginning of a sentence and get the rest of the string to continue the command

For example:

  

/ talk test1 test2 test3

Detect the "/ talk" command and say "test1 test2 test3"

    
asked by anonymous 06.04.2018 / 15:49

2 answers

0

Hello, if your variable that contains the sentence ALWAYS start with "/", I say, for example, if the / command is not from the 4th character, you can do this with the function strpos .

A working example would be:

$var_texto = "/comando teste1 teste2 teste3";

// retorna true se $var_texto começar com /
if(strpos($var_texto, "/") === 0){
    $array_texto = explode(" ", $var_texto);
    $comando = $array_texto[0];

    // Remove o comando dos arrays
    unset($array_texto[0]);

    // Obtem a string final
    $continuacao = implode(' ', $array_texto);
}

This way you will have the command is $comando and its parameters are in $continuacao

    
06.04.2018 / 15:56
1

You can also use preg_match_all :

$var_texto = "/comando teste1 teste2 teste3";

if(preg_match_all('/(\/\w+)|(\w+\s\w).*/', $var_texto, $matches)) {
    echo $matches[0][0], PHP_EOL; // -> /comando
    echo $matches[0][1], PHP_EOL; // -> teste1 teste2 teste3   
} else {
    echo 'Fora do padrão', PHP_EOL;
}

Regex:

(\/\w+)     -> captura a barra "/" e caracteres alfanuméricos até um espaço
(\w+\s\w).* -> captura caracteres alfanuméricos separados por espaço, tudo junto

See Ideone

    
06.04.2018 / 16:55