4

I am using the preg_replace function in PHP and am trying to replace urls that users submit with bit.ly shortened links:

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

This will show only the comment and "wipe out" the url. The question is how can I get the URL from the text and append it later?

hakre
  • 193,403
  • 52
  • 435
  • 836
John Doe
  • 3,559
  • 15
  • 62
  • 111

1 Answers1

3

preg_replace_callback()

Example from 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);

?>

define a callback function that replaces the URL. It will receive the matches as a parameter, and inside you will form, depending on those matches, a replacement string.

Alex
  • 14,338
  • 5
  • 41
  • 59