开发者

preg_replace to remove all words beginning with http:// and ending with a space

开发者 https://www.devze.com 2022-12-16 08:19 出处:网络
i got an idea to remove all links from a string with PHP. i nee开发者_Python百科d a preg_replace to remove and strip all words beginning with :

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

i nee开发者_Python百科d 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


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.


$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);


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

/(http:\/\/(.*?)\s)/i


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


Solution from Cletus doesn't work properly because . (dot) is also word boundary so we should use whitespace marker \s instead of word bouadry at the end:

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

精彩评论

暂无评论...
验证码 换一张
取 消