Jump to content

Need help with regular expression using "PREG_REPLACE"


asyadiqin

Recommended Posts

Hi all, sorry if someone have posted this solution elsewhere but I couldn't find any when i search the forum.

 

I need to be able to replace double slashes "//"  in a url string. Example as follows

 

to

 

I was told that this can be done using preg_replace, but the problem is to write a regular expression to ignore and not replace the double quotes in "http://". I am not very good with regular expression and have tried but failed miserably. I am not sure if this is the correct route to perform this task but any help is greatly appreciated.

 

Currently, as a workaround, I just explode the url string, replace the double quotes and add "http://" to the string, but I am curious to know if this can be done with just a single line of PHP code. Thanks.

 

 

 

 

php isn't ti basic, where shorter lines of code yield more efficiency

rather if possible a non-regex solution is most likely better, but shorter lines are easier on the eyes :)

 

have tried but failed miserably

here's a nice tut:

http://www.phpfreaks.com/tutorials/52/0.php

search "regex lookaheads lookbehinds" in google

 

Pattern:

~(?<!http:)//~

 

Visualize it:

http://nancywalshee03.freehostia.com/regextester/regex_tester.php?seeSaved=mgup3cnz

 

Code it:

$url = 'http://www.mydomain.com/with//double//quotes/';
$url = preg_replace('~(?<!http:)//~', '', $url);
echo $url;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.