hsatterwhite
hsatterwhite

Reputation: 7355

How to use a positive lookahead to replace all, but one http(s):// in a string?

How to use a positive lookahead to replace all, but one http(s):// in a string?

I have user input that some times includes multiple http:// or https://'s in the string e.g. http://http://wwww.site.com/ and I need to remove all instances, BUT one. I've read about using a positive lookahead in a regex pattern, but cannot seem to make it work.

I've tried the following:

preg_replace( 'https?://(?=.*https?://)', '', $url );

Upvotes: 1

Views: 82

Answers (2)

mimipc
mimipc

Reputation: 1374

This could work :

<?php

$text = 'http://https://http://http://https://abc.com';
$text = preg_replace('#(https?://)+https?://#iU', '', $text);
echo $text;

Upvotes: 2

D&#233;j&#224; vu
D&#233;j&#224; vu

Reputation: 28850

$url = preg_replace("#(https?://)+#", "$1", $url);

Upvotes: 4

Related Questions