I’m trying to replace:
*facebook.com/
with http://graph.facebook.com/
I need to be able to group anything before the facebook.com part into an optional group.
I can’t just replace facebook.com with graph.facebook.com because the incoming URL may contain https.
Here’s what I have but misses anything that doesn’t have http[s]://.
<?php
$fb_url = preg_replace('/http[s]*:\/\/[www.]*facebook.com\//', 'http://graph.facebook.com/', 'facebook.com/some/segments');
echo $fb_url;
?>
Addressing your question specifically:
You can make any single character (or a group of characters) optional by adding a
?after it in your regex.A couple of tips from looking at your code:
/characters, simplify your life by using a different delimiter (for example#). You aren’t required to use a forward slash..dot metacharacter because it matches ANY single character, so your expressionwww.could conceivably match www9 or anything else along those lines[...]are for matching a range of characters. If you want to match specifically the text www. you should use a non-captured group like(?:www\.)and make it optional by adding the?after it like(?:www\.)?So, those tips in mind, try …