How to use the PHP preg_match command

Asked

Viewed 3,832 times

0

How do I use the preg_match to detect a string where you have 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 take the rest of the string to continue the command

For example:

/speak test 1 test 2 test 3

Detect the "/speak" command and say "teste1 teste2 teste3"

2 answers

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

Check it out at Ideone

  • 1

    I would still recommend treating the return of the function on if, something thus, to ensure that the format was suitable, but still better than explode. +1

  • Very good. Obg!

0


Hello, if your variable containing the phrase starts ALWAYS with "/", I say, for example, if the /command is not from the 4th character, it is possible to do this with the function strpos.

An example of functioning 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);
}

That way you’ll have that command is $comandoand its parameters are in $continuacao

  • almost worked 100%! gave error on the line of unset PHP Parse error: syntax error, Unexpected '$array_text' (T_VARIABLE), expecting '('

  • Oops. What’s missing?

  • was just the syntax: unset ($array_text[0]); thanks a lot. saved cool!

  • Wow, true. I edited the answer. VLW :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.