September 17, 2014

September 17, 2014
In this article, we are going to discuss about How to change the URL and Email as Hyperlink in CodeIgniter. We might have seen plain text get converted to hypertext when we type it. For example, In gtalk when we type www.phpcmsframework.com it automatically changes as a hyperlink and point to http://www.phpcmsframework.com, Same way, when we type an email address it is automatically converted to mailto:phpcmsframework@gmail.com.

These kind of conversion can be made using PHP string replace function. We have to check the whole string where it has the url or email address, then we have to replace the url with anchor tag.

In CodeIgniter the easiest way to do it is to use the URL helper. First step is to load the URL helper.

$this->load->helper('url');

Then the next thing to do is to use a function

auto_link();

This function makes our life easier. We have to pass the string that we need to find for url and email.

$string = "This is a sample text and its url is www.phpcmsframework.com";
echo auto_link($string);

The output of the above code is Today I visited a useful blog about web development and its url is www.phpcmsframework.com

The same way email id is also auto linked. We can also restrict the automation only to url or email. This can be done by

echo auto_link($string,'email');
echo auto_link($string,'url');

In case if we want the link to open in a new tab, we can do it by adding a third parameter which can be either TRUE or FALSE.

echo auto_link($string, 'both', TRUE);

Here second parameter 'both' indicates that both 'email' and 'url' has to be automatically converted to hypertext.

0 comments:

Post a Comment