Good software enables us to take a lot of niceties for granted. Intelligent interfaces handle all the simple tasks so that we donât need to worry about them. For example, when I type âwww.desktopped.comâ into an email or an instant message, I expect that it will be clickable on the other end without having to manually add in HTML tags. Another example is parsing text from a twitter feed. For example, â@desktopped is a blog about the #computersâ, we expect both @desktopped and #computers to be links.
The ability to âlinkifyâ text is a great tool to have when developing a blog or website. Possible uses include:
- Turning URLs clickable in content, comments, and anywhere else
- Turning valid email addresses clickable
- Turning twitter text clickable so that @desktopped, #computers, www.desktopped.com all become links.
To search a string for patterns, such as strings that begin with âhttp://â or â@â is an ability that can be applied in almost endless ways to improve the way we process and display data.
How can we do this? The best way with PHP is to use a universal pattern matching syntax called regular expressions and some useful PHP functions.
Regular Expressions BasicsA regular expression is a pattern string that represents a set of strings by using a variety of special characters.
The Basic Special Characters- | connects two possible values and will turn up a match if the string matches either. For example hi|hello matches the strings âhiâ and âhelloâ
- () are used to group values and set order of operations. For example, br(i|y)an will match both âbrianâ and âbryanâ.
- [] are used to match a single character that appears inside the brackets. [abc] will match âaâ, âbâ, or âcâ, but not âdâ.
- * will turn up a match if there is zero or more of the preceding element. The string go*gle will match âggleâ, âgogleâ, âgoogleâ, âgooogleâ, etc.
- + will turn up a match if there is one or more of the preceding element. The string go+gle will match âgogleâ, âgoogleâ, gooogleâ, etc.
- ? will turn up a match if there is zero or one of the preceding character. The string desktopp?ed will match both âdesktoppedâ and âdesktopedâ.
- \w will match and âwordâ character, which translates to any character alphanumeric or â_â
- \n \r and \t will match a new line, carriage return and tab respectively.
A full reference for special characters can be found here:
http://www.php.net/manual/en/function.preg-replace.php#89364
PHP Function: preg_replaceThe preg_replace function in PHP will take a regular expressions pattern, a replacement string, and the text to be examined as arguments. It will check the input text against the pattern and then if thereâs a match it will place certain pieces of the input text into the replacement string.
The pieces that are placed into the replacement string are determined by what is in parenthesis in the pattern string. They are then referenced in the replacement string by using $0, $1, $2, etc., where the $n matches the nth parenthesized pattern.
A Simple Example$text= 'My name is Brian'; $pattern = 'My name is (Brian|Sam|Zach)'; $replacement = '$1 is a pretty cool guy.'; echo preg_replace($pattern, $replacement, $text);The code will output âBrian is a pretty cool guy.â If $text was âMy name is Zachâ, the output would be âZach is a pretty cool guy.â If $text was âMy name is Nickâ, thereâd be no match and the original text would be returned; âMy name is Nickâ.
Useful Regex FunctionsThis function will turn all URLs in a body of text into clickable links
function link_it($text) { $text= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" >$3</a>", $text); $text= preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" >$3</a>", $text); $text= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:$2@$3\">$2@$3</a>", $text); return($text); }This function will turn all pound signs (#) and at-sign (@) into hash tag and @reply links in a twitter feed.
function twitter_it($text) { $text= preg_replace("/@(\w+)/", '<a href="http://www.twitter.com/$1" target="_blank">@$1</a>', $text); $text= preg_replace("/\#(\w+)/", '<a href="http://search.twitter.com/search?q=$1" target="_blank">#$1</a>',$text); return $text; }This function finds strings in your post body that youâve identified with the pattern :tagname: and turns them into tag searches on your blog. For example: âThis post is about :PHP:.â will result in âThe post is about PHPâ.
function tag_it($text) { $text= preg_replace("/:(\w+):/", '<a href="http://www.buildinternet.com/tag/$1/" target="_blank">$1</a>',$text); return $text; }This function will highlight search terms in search result titles on your Wordpress blog. Pass an array of keywords and it will do the rest. (Must be used inside the loop)
function highlight_terms($keys_array) { $title = get_the_title(); return preg_replace('/('.implode('|', $keys_array) .')/iu', '<span class="highlight">$0</span>', $title); }The function will take any string (usually a page title) and generate a URL slug.
function create_slug($string) { $string= strtolower(trim($string)); $string= preg_replace('/[^a-z0-9-]/', '-', $string); $string= preg_replace('/-+/', "-", $string); return $string; }Further ReadingRegular Expressions Resource:
http://www.regular-expressions.info
PHP pre_replace Manual:
http://php.net/manual/en/function.preg-replace.php
Powered by WizardRSS | Full Text RSS Feeds