PHP Strings

Posts about manipulating strings in different ways in PHP

PHP Logo

Preparing A URL With PHP

12th June 2008 - 3 minutes read time

There might be many instances where you will create a program in PHP that takes a URL as input and does something with the address. This might be a site analysis or an image resize, but whatever the use is, you need to be sure that the URL will work or at least has the same format.

What users tend to leave out of a URL string is the http:// bit at the start. You could validate the URL to force the user to do this, but you will end up annoying a few people. By far the best way of making sure that the URL has the http:// bit at the start is by adding it behind the scenes. The best way to this is to remove the http:// from the start of the string, even if it isn't there and then add it back on.

PHP Logo

Getting An Excerpt Of Text With PHP

1st June 2008 - 4 minutes read time

I have talked before about truncating strings to include whole words, but what if you want to have complete sentences? The following function will truncate a string the number of words specified and until the sentence ends.

function excerpt($paragraph, $limit)
{
 $tok = strtok($paragraph, " ");
 while ($tok !== false) {
  $text .= " ".$tok;
  $words++;
  if (($words >= $limit) && ((substr($tok, -1) == "!") || (substr($tok, -1) == ".") || (substr($tok, -1) == "?"))) {
   break;
  }
  $tok = strtok(" ");
 }
 return ltrim($text);
}

Using this function you can create an excerpt of any text you want, as long as it has a sentence in it. Take the following section of text.

PHP Logo

Transform Text Links Into Anchors

28th May 2008 - 2 minutes read time

Using the strip_tags() function on any user generated input should be common practice in order to stop users putting in odd bits of HTML and messing up your nicely coded HTML. You might want to allow anchor tags to be used, which is fine, but some users might use this to include onmouseover and other events in order to run JavaScript annoyances on the page.

So after stripping all tags from your text you can then run the following function to turn any links into anchor elements. This will work with any plain text that you want to use it on.

PHP Logo

Mask Email With ASCII Character Codes In PHP

28th April 2008 - 2 minutes read time

Hiding your email address in an image is the best way of encrypting your email, but if your server doesn't support the GD2 library, or if you don't want to use it, then you might want to look at a different way of doing this.

The easiest way to encrypt your email address is to turn every character into the ASCII code equivalent and use this to display the text in HTML by putting a &# in front of each character. Here is a function that takes a string and turns it into HTML encoded text.

function maskEmail($email) {
 $hiddenEmail = '';
 $length = strlen($email);    
 
 for ($i = 0;$i < $length; $i++) {
  $hiddenEmail .= "&#".ord($email[$i]).";";
 }
 
 return $hiddenEmail;
}

To use this just feed an email address into it.

PHP Logo

Turning ASCII Text Into HTML With PHP

25th April 2008 - 2 minutes read time

Providing a text box for users to type information in is very common, but usually people want to include line breaks and links with the text and they expect the site to lay it out just as they had intended it. The following function will turn any ASCII text string into the approximate HTML equivalent.

PHP Logo

Cut A String To A Specified Length With PHP

17th April 2008 - 2 minutes read time

Cutting a string to a specified length is accomplished with the substr() function. For example, the following string variable, which we will cut to a maximum of 30 characters.

$string = 'This string is too long and will be cut short.';

The substr() function has three parameters. The first is the string, the second is where to start cutting from and the third is the amount of characters to cut to. So to cut to 30 characters we would use the following.

$string = substr($string,0,30);

The string variable is now set to the following.

This string is too long and wi

This example highlights the major problem with this function in that it will take no notice of the words in a string. The solution is to create a new function that will avoid cutting words apart when cutting a string by a number of characters.

PHP Logo

Faster Way Of Checking String Length With PHP

9th April 2008 - 1 minute read time

If you want to know the length of a string in PHP you would normally turn to the strlen() function which simply tells you the length of the string.

$string = 'this is a string';
$strLength = strlen($string);

To use this to check the length of the string use the following example.

$string = 'this is a string';
if (strlen($string) < 20) {
 // code here
}

A quicker way of looking at the length of a string would be to use the isset() function in conjunction with the curly braces {} used for locating character from a string.

$string = 'this is a string';
if (!isset($string{20})) {
 // string too short
}

Because isset() is a language construct it works quicker than strlen() so this comparison has almost no overhead at all.

PHP Logo

Creating A URI Slug With PHP

28th March 2008 - 2 minutes read time

The use of mod_rewrite on a site can have a powerful effect on search engine positioning, but to do it properly you will need to create a "slug" for each page. A slug is a lowercase alphanumeric version of the page title, with any spaces removed.

To get a slug you will need to use a function to turn a readable page title into a string that can be used as part of a URI.

This function is taken from Bramus and his excellent article about creating a post slug, and it does the job very nicely.

PHP Logo

Extract Links From A HTML File With PHP

6th March 2008 - 1 minute read time

Use the following function to extract all of the links from a HTML string.

function linkExtractor($html)
{
 $linkArray = array();
 if(preg_match_all('/<a\s+.*?href=[\"\']?([^\"\' >]*)[\"\']?[^>]*>(.*?)<\/a>/i', $html, $matches, PREG_SET_ORDER)){
  foreach ($matches as $match) {
   array_push($linkArray, array($match[1], $match[2]));
  }
 }
 return $linkArray;
}

To use it just read a web page or file into a string, and pass that string to the function. The following example reads a web page using the PHP CURL functions and then passes the result into the function to retrieve the links.