tags:

views:

198

answers:

4

Hi,

i got an idea to remove all links from a string with PHP.

i need a preg_replace to remove and strip all words beginning with :

http:// or https:// or www. or www3. or ftp://

and ending with a white space.

example : hello http://dsqdsq.com/fdsfsd?fsdflsd enjoy !

it's will be : hello enjoy !

Thanks

+2  A: 
$string = 'hello http://dsqdsq.com/fdsfsd?fsdflsd enjoy !';
$stripped_string = preg_replace('; ((ftp|https?)://|www3?\.).+? ;', ' ', $string);

Update: Here is with \b instead of spaces, which will work better. Big thanks to cletus!

$string = 'hello http://dsqdsq.com/fdsfsd?fsdflsd enjoy !';
$stripped_string = preg_replace(';\b((ftp|https?)://|www3?\.).+?\b;', ' ', $string);
Emil Vikström
Dont forget ftp://
Mr-sk
Doesn't this require a space at the beginning - i.e. lines starting with a URL won't match?
Simon
A: 

something like this? just off the top of my head without checking

/(http:\/\/(.*?)\s)/i
Funky Dude
+2  A: 

I would do it this way:

$output = preg_replace('!\b((https?|ftp)://)?www3?\..*?\b!', '', $input);

which:

  • Starts at a word boundary (\b);
  • Optionally begins with http://, https:// or ftp://; and
  • Has a domain name beginning with www. or www3.

That and all text up to the next word boundary is then deleted.

Note: Using \b is generally superior than checking for spaces. \b is a zero-width (meaning it consumes no part of the input) that matches the beginning of the string, the end of the string, the transition from a word to a non-word character or the transition from a non-word to a word character.

cletus
+1 for \b ! Really nice operator to know! You learn something new every day!
Emil Vikström
A: 

hmm.. try

$pattern=array(
        '`((?:https?|ftp)://\S+[[:alnum:]]/?)`si',
        '`((?<!//)(www\.\S+[[:alnum:]]/?))`si'
        );
$output = "http://$1";
$input = // set some url here;
preg_replace($pattern,$output,$input);
streetparade