Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / PHP

preg_match()

Procura a primeira correspondência.

Versão: PHP 8.4; repository runtime, production runtime not attested

Sintaxe

preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int|false

Procura a primeira correspondência. Devolve 1 quando a encontra, 0 quando não há nenhuma e false em caso de erro de compilação ou execução. O índice zero contém a correspondência completa. PREG_OFFSET_CAPTURE acrescenta a posição em bytes mesmo em UTF-8. O parâmetro $offset também conta bytes. Com o modificador u uma posição dentro de um caráter UTF-8 dá false e PREG_BAD_UTF8_OFFSET_ERROR.

Assinatura

preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int|false

Saída do exemplo

[1,[["A42",3],["42",4]],0]
[false,true]

Exemplos

<?php
$input="é A42"; $found=preg_match("~A(\\d+)~u",$input,$m,PREG_OFFSET_CAPTURE);
echo json_encode([$found,$m,preg_match("~Z~",$input)]);
$bad=preg_match("~.~u","é",$matches,0,1); echo "\n",json_encode([$bad,preg_last_error()===PREG_BAD_UTF8_OFFSET_ERROR]);

Resultado

[1,[["A42",3],["42",4]],0]
[false,true]

Fontes