Ricerca…


Sintassi

  • preg_replace($pattern, $replacement, $subject, $limit = -1, $count = 0);
  • preg_replace_callback($pattern, $callback, $subject, $limit = -1, $count = 0);
  • preg_match($pattern, $subject, &$matches, $flags = 0, $offset = 0);
  • preg_match_all($pattern, $subject, &$matches, $flags = PREG_PATTERN_ORDER, $offset = 0);
  • preg_split($pattern, $subject, $limit = -1, $flags = 0)

Parametri

Parametro Dettagli
$pattern una stringa con un'espressione regolare (modello PCRE)

Osservazioni

Le espressioni regolari di PHP seguono gli standard di pattern PCRE, che derivano dalle espressioni regolari di Perl.

Tutte le stringhe PCRE in PHP devono essere racchiuse tra delimitatori. Un delimitatore può essere qualsiasi carattere non alfanumerico, non backslash, non di spazio bianco. I delimitatori popolari sono ~ , / , % per esempio.

I pattern PCRE possono contenere gruppi, classi di caratteri, gruppi di caratteri, asserzioni look-ahead / look-behind e caratteri di escape.

È possibile utilizzare i modificatori PCRE nella stringa $pattern . Alcuni comuni sono i (case insensitive), m (multiline) e s (il punto metacarattere include newline). Il modificatore g (globale) non è permesso, preg_match_all invece la funzione preg_match_all .

Le corrispondenze con le stringhe PCRE vengono eseguite con stringhe numerate con prefisso $ :

<?php

$replaced = preg_replace('%hello ([a-z]+) world%', 'goodbye $1 world', 'hello awesome world');

echo $replaced; // 'goodbye awesome world'

String matching con espressioni regolari

preg_match controlla se una stringa corrisponde all'espressione regolare.

$string = 'This is a string which contains numbers: 12345';

$isMatched = preg_match('%^[a-zA-Z]+: [0-9]+$%', $string);
var_dump($isMatched); // bool(true)

Se passi un terzo parametro, verrà popolato con i dati corrispondenti dell'espressione regolare:

preg_match('%^([a-zA-Z]+): ([0-9]+)$%', 'This is a string which contains numbers: 12345', $matches);
// $matches now contains results of the regular expression matches in an array.
echo json_encode($matches); // ["numbers: 12345", "numbers", "12345"]

$matches contiene una matrice dell'intera corrispondenza, quindi sottostringhe nell'espressione regolare delimitata da parentesi, nell'ordine di offset della parentesi aperta. Ciò significa che se si ha /z(a(b))/ come espressione regolare, l'indice 0 contiene l'intera sottostringa zab , l'indice 1 contiene la sottostringa delimitata dalle parentesi esterne ab e l'indice 2 contiene le parentesi interne b .

Dividi la stringa in array con un'espressione regolare

$string = "0| PHP 1| CSS 2| HTML 3| AJAX 4| JSON";

//[0-9]: Any single character in the range 0 to 9
// +   : One or more of 0 to 9
$array = preg_split("/[0-9]+\|/", $string, -1, PREG_SPLIT_NO_EMPTY);
//Or
// []  : Character class
// \d  : Any digit
//  +  : One or more of Any digit
$array = preg_split("/[\d]+\|/", $string, -1, PREG_SPLIT_NO_EMPTY);

Produzione:

Array
(
    [0] =>  PHP
    [1] =>  CSS 
    [2] =>  HTML 
    [3] =>  AJAX 
    [4] =>  JSON
)

Per dividere una stringa in una matrice basta passare la stringa e preg_split(); per preg_split(); per abbinare e cercare, aggiungendo un terzo parametro ( limit ) consente di impostare il numero di "corrispondenze" da eseguire, la stringa rimanente verrà aggiunta alla fine dell'array.

Il quarto parametro è ( flags ) qui usiamo il PREG_SPLIT_NO_EMPTY che impedisce al nostro array di contenere chiavi / valori vuoti.

Sostituzione delle corde con espressione regolare

$string = "a;b;c\nd;e;f";
// $1, $2 and $3 represent the first, second and third capturing groups
echo preg_replace("(^([^;]+);([^;]+);([^;]+)$)m", "$3;$2;$1", $string);

Uscite

c;b;a
f;e;d

Cerca tutto tra il punto e virgola e inverte l'ordine.

Partita Global RegExp

È possibile eseguire una corrispondenza RegExp globale utilizzando preg_match_all . preg_match_all restituisce tutti i risultati corrispondenti nella stringa dell'oggetto (in contrasto con preg_match , che restituisce solo il primo).

La funzione preg_match_all restituisce il numero di corrispondenze. Le $matches terzo parametro $matches conterranno le partite in formato controllato da flag che possono essere fornite nel quarto parametro.

Se viene fornito un array, $matches conterrà array in un formato simile che si otterrebbe con preg_match , tranne che preg_match ferma alla prima corrispondenza, dove preg_match_all iterazioni sulla stringa finché la stringa non viene interamente consumata e restituisce il risultato di ogni iterazione in una matrice multidimensionale , quale formato può essere controllato dalla bandiera nel quarto argomento.

Il quarto argomento, $flags , controlla la struttura di $matches matrice. La modalità predefinita è PREG_PATTERN_ORDER e i possibili flag sono PREG_SET_ORDER e PREG_PATTERN_ORDER .

Il seguente codice dimostra l'uso di preg_match_all :

$subject = "a1b c2d3e f4g";
$pattern = '/[a-z]([0-9])[a-z]/';

var_dump(preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER)); // int(3)
var_dump($matches);
preg_match_all($pattern, $subject, $matches); // the flag is PREG_PATTERN_ORDER by default
var_dump($matches);
// And for reference, same regexp run through preg_match()
preg_match($pattern, $subject, $matches);
var_dump($matches);

Il primo var_dump di PREG_SET_ORDER fornisce questo risultato:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(3) "a1b"
    [1]=>
    string(1) "1"
  }
  [1]=>
  array(2) {
    [0]=>
    string(3) "c2d"
    [1]=>
    string(1) "2"
  }
  [2]=>
  array(2) {
    [0]=>
    string(3) "f4g"
    [1]=>
    string(1) "4"
  }
}

$matches ha tre matrici annidate. Ogni matrice rappresenta una corrispondenza, che ha lo stesso formato del risultato di ritorno di preg_match .

Il secondo var_dump ( PREG_PATTERN_ORDER ) fornisce questo output:

array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(3) "a1b"
    [1]=>
    string(3) "c2d"
    [2]=>
    string(3) "f4g"
  }
  [1]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "4"
  }
}

Quando lo stesso regexp viene eseguito tramite preg_match , viene restituito il seguente array:

array(2) {
  [0] =>
  string(3) "a1b"
  [1] =>
  string(1) "1"
}

La stringa sostituisce con il callback

preg_replace_callback funziona inviando ogni gruppo di acquisizione corrispondente al callback definito e lo sostituisce con il valore di ritorno del callback. Questo ci permette di sostituire stringhe basate su qualsiasi tipo di logica.

$subject = "He said 123abc, I said 456efg, then she said 789hij";
$regex = "/\b(\d+)\w+/";

// This function replaces the matched entries conditionally 
// depending upon the first character of the capturing group
function regex_replace($matches){
    switch($matches[1][0]){
        case '7':
            $replacement = "<b>{$matches[0]}</b>";
            break;
        default:
            $replacement = "<i>{$matches[0]}</i>";
    }
    return $replacement;
}

$replaced_str = preg_replace_callback($regex, "regex_replace", $subject);

print_r($replaced_str);
# He said <i>123abc</i>, I said <i>456efg</i>, then she said <b>789hij</b> 


Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow