Found on the digitalpoint forums at http://forums.digitalpoint.com/showthread.php?t=687808
I want to auto-magically change the color of a URL in the middle, like this
domain_name.com
There is no www so the period can be used as delimiter. The URL is generated by PHP so I can not simply use HTML.
Using Regular Expressions in PHP we can identify the part of the text that contains the domain name and wrap it in a span.
Test String: “here is the text surrounding dom-ain.com text and a generic .com name alongwith do.main.net, domain.org and del.co.uk”
Using preg_replace with regular expressions in PHP
<?php
$string = ‘here is the text surrounding dom-ain.com text and a generic .com name alongwith do.main.net, domain.org and del.co.uk’;
$pattern = ‘/([0-9a-zA-Z.\-]+)+(.com|.net|.org|.co.uk)/’;
$replacement = ‘<span style=”color:#F00″>${1}</span>${2}’;
echo preg_replace($pattern, $replacement, $string);?>
Output: “here is the text surrounding dom-ain.com text and a generic .com name alongwith do.main.net, domain.org and del.co.uk”
From http://us.php.net/preg-replace
preg_replace — Perform a regular expression search and replace
mixed preg_replace( mixed $pattern ,mixed $replacement ,mixed $subject [,int $limit [,int &$count ]] )
Searches $subject for matches to $pattern and replaces them with $replacement.
The $string will be the text that contains your domain names.
$pattern is a regular expression pattern I constructed following the handy cheat sheet at http://regexlib.com/CheatSheet.aspx and testing it online at http://regexlib.com/RETester.aspx
Deconstructing the regular expression
‘/
- start
([0-9a-zA-Z.\-]+)+
- match all characters from 0-to-9 a-to-z A-toZ and ‘.’ and ‘-’. These are the valid characters for domain names. The ‘+’ signs mean atleast 1 or more of that sequence must be matched
(.com|.net|.org|.co.uk)
- Very literally a ‘.com’, ‘.org’ or ‘.co.uk’ must follow the previous set of characters. You can add additional TLDs here, seperated by a pipe(’|') which acts as an ‘OR’.
/’
- end
The $replacement is a string with the span tag wrapped around ${1} and ${2}, these represent the 1st and 2nd matched sequences, for example ‘domain’ and ‘.com’. ${0} would match the entire ‘domain.com’ string.
Even for advanced users, here are some resources to help you get started using them.
http://regexlib.com/CheatSheet.aspx - Cheat Sheet
http://regexlib.com/RETester.aspx - Online Tester
http://www.zytrax.com/tech/web/regex.htm - A Simple User Guide
http://www.amk.ca/python/howto/regex/ - Detailed Regular Expression HOWTO
OR follow on Twitter
Twitter.com/DeDestruct
Leave a reply