Page 1 of 1

replacing a url

Posted: Fri Mar 30, 2012 1:58 am
by azycraze
hi experts,
I need to replace every url in a text string with my url.
any of the three below patterns
************
http://www.example.com/
http://example.com/
http://www.example.com/
**************
in the string should be replaced by
$replaceby="<a href='eee.com'>loop</a>";
the $pattern will be an array with 3 above mentioned patterns.

Re: replacing a url

Posted: Fri Mar 30, 2012 2:14 am
by ragax
Hi azycraze,

Have a look at this.
I couldn't find the difference between patterns 1 and 3, though.

Input:

'pattern 1: http://www.example.com/
pattern 2: http://example.com/
pattern 3: http://www.example.com/'


Code:

Code: Select all

<?php
$regex=',http://[^/]+/,';
$string='pattern 1: http://www.example.com/
pattern 2: http://example.com/
pattern 3: http://www.example.com/';
$string=preg_replace($regex,"<a href='eee.com'>loop</a>",$string);
echo htmlentities($string);
?>
Output:

pattern 1: <a href='eee.com'>loop</a> pattern 2: <a href='eee.com'>loop</a> pattern 3: <a href='eee.com'>loop</a>


The regex replaces strings like these: http://STUFF/
Given the nature of the patterns, I did not see a point adding an optional www (we are replacing the string with or without it). If this is wrong, at least this gets us started, you will be able to refine your request.

Let me know if you have questions or need tweaking.

:)

Re: replacing a url

Posted: Fri Mar 30, 2012 10:15 am
by azycraze
sorry for the mistake.
actually the third pattern was "www.example.com".
also in your regex if the url does not contain a '/' t the end of the url for eg:- http://www.example.com ,the replacement will not work.

Re: replacing a url

Posted: Fri Mar 30, 2012 2:55 pm
by ragax
also in your regex if the url does not contain a '/' t the end of the url
That's right, but that's not a mistake, it's exactly what you specified. :)

The following pattern addresses these two tweaks (url either starts with http:// or www., final slash is optional).

Code: Select all

$regex='~(?:http://|www\.)(?:[[:alpha:]-]++\.)++[[:alpha:]]{2,6}/?~';
Note that at the moment:
- you said "example.com", so I wasn't sure which chars you want to allow. At the moment, the only chars allowed in the core of the url are letters and dashes, e.g: my-site.com. If you also want numbers, change the first "alpha" to "alnum", and if you don't want dashes, remove it a few chars after the first "alpha".
- in the regex the domain can be from two to six letters (e.g. .us, .com, .museum), don't know how long domains can be these days, so you tweak that to suit your needs with the {2,6}
- The pattern will work with www.mail.server.co.uk

Wishing you a fun weekend.

Re: replacing a url

Posted: Fri Mar 30, 2012 11:46 pm
by azycraze
thanks,it really worked

Re: replacing a url

Posted: Sat Mar 31, 2012 12:01 am
by ragax
You're welcome, glad to hear it, thanks for letting me know.