views:

56

answers:

5
preg_replace('/http:///ftp:///', 'https://', $value);

http:// and ftp:// inside $value should be replaced with https://

This code gives error:

preg_replace() [function.preg-replace]: Unknown modifier '/' 

What is a true regex for this task?

+1  A: 

Use another delimiter character, like '#', for instance.

preg_replace('#/http://|ftp://#', 'https://', $value);

And do not confuse / and |

greg0ire
+3  A: 

Try using a different delimiter:

preg_replace('#http://|ftp://#', 'https://', $value);

or (less recommended) escape every occurrence of the delimiter in the regex:

preg_replace('/http:\/\/|ftp:\/\//', 'https://', $value);

You are searching for the pattern http:///ftp:// which really does not make much sense, may be you meant http://|ftp://

Understanding the error Unknown modifier '/' :

In your regex '/http:///ftp:///', the first / is considered as starting delimiter and the / after the : is considered as the ending delimiter. Now we know we can provide modifier to the regex to alter its default behavior. Some such modifiers are:

  • i : to make the matching case insensitive
  • m : multi-line searching

But what PHP sees after the closing delimiter is another / and tries to interpret it as a modifier but fails, resulting in the error.

preg_replace returns the altered string.

$value = 'http://foo.com';
$value = preg_replace('#http://|ftp://#', 'https://', $value);
// $value is now https://foo.com
codaddict
first one doesn't work
Happy
Are you collecting the return value of `preg_replace` as I've shown above ?
codaddict
+1  A: 
preg_replace('!(http://|ftp://)!', 'https://', $value);

Long story: Regexp needs to be enclosed in delimiters, and those have to be unique inside the whole regexp. If you want to use /, then the remaining /-s inside the regexp need to be escaped. This however makes the syntax look a bit ugly. Luckily you can use any character as delimiter. ! works fine, as will other characters.

The rest of the regexp just lists two options, either of which will be replaced with the second parameter.

Anti Veeranna
can you explain this regex?
Happy
+1  A: 
preg_replace('|http:\/\/ftp:\/\/', 'https://|', $value);
kgb
+1  A: 

Use this instead:

preg_replace('-(http|ftp)://-', 'https://', $value);

Or

preg_replace('/(http|ftp):\/\//', 'https://', $value);
pyrony