nadya nadya - 28 days ago 21
PHP Question

preg replace https won't work

I want to remove http:// & https://

I add this inline:

^https?://


preg_replace(array('/(?i)\b((^https?:////\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))/', '/(^|[^a-z0-9_])@([a-z0-9_]+)/i', '/(^|[^a-z0-9_])#(\w+)/u')


Try and fail, syntax error?

Answer

If you just want to remove http:// and https:// (which is your question), this will do the trick:

$str = preg_replace('/(https?:\/\/)/', '', 'http://example.com');

If you only want to remove them if a string starts with either of those protocols:

$str = preg_replace('/^(https?:\/\/)/', '', 'http://example.com');

The ^ right after the initial delimiter means "start of the string".

Comments