Domanda

Sto usando la funzione preg_replace in PHP e sto cercando di sostituire gli URL che gli utenti inviano con collegamenti bit.ly:

$comment = preg_replace( '/(http|ftp)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/i', '', $strText );
.

Questo mostrerà solo il commento e "cancella" l'URL.La domanda è come posso ottenere l'URL dal testo e aggiungerlo più tardi?

È stato utile?

Soluzione

preg_replace_callback ()

Esempio da php.net:

<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
  // as usual: $matches[0] is the complete match
  // $matches[1] the match for the first subpattern
  // enclosed in '(...)' and so on
  return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
            "|(\d{2}/\d{2}/)(\d{4})|",
            "next_year",
            $text);

?>
.

Definisci una funzione di callback che sostituisce l'URL.Riceverà le partite come parametro, e dentro si formerai, a seconda delle partite, una stringa di ricambio.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top