PHP loop through string

PHP loop through string



PHP loop through string - If you made it to this page, you probably want to know how to loop through a string in PHP and evaluate its every character. Let's say you have a string $string = "abcde", and you want to evaluate its every character and perhaps replace it with something. Looping through strings is very easy in PHP.

First, let's demonstrate where looping through a string can be handy and then let's explain how it can be done.

Why would I want to loop through string?

Before we start explaining how to loop through a string, we should provide an example demonstrating where it can be used. If you look at how email addresses are displayed at websites, most websites provide email addresses in their raw (readable) format. Your email address may be coded into the web page as

<a href="mailto:joe_smith@example.com">joe_smith@example.com</a>

There is nothing wrong about displaying email addresses like this on the web but one thing: web crawlers are able to harvest your email address and then flood it with spam. How could we protect web pages from web crawlers getting your email address? There are many ways to prevent email address harvesting, and one of the quick and easy ways is to encode your email address as dec or hex entities. Take a look at the following example:

<a href="mailto:&#106;&#111;&#101;&#95;&#115;&#109;&#105;&#116;&#104;&#64;&#101;
&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;">&#106;&#111;&#101;&#95;
&#115;&#109;&#105;&#116;&#104;&#64;&#101;
&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;</a>

The Gibberish code provided above is the same as the joe_smith@example.com email address above just in different language. Even though this Gibberish code is not readable to human now, it will be displayed as joe_smith@example.com at the website. The Gibberish code above is displayed by a browser exactly the same way like the nice mailto:joe_smith.

We are not saying that encoding your email address in entities will completely protect your email address, it will not, but it should at least make the job for spammers harder. Anything that makes spammers' job harder is good and worth trying.

How did we do this? We stored the readable email address into a string and then exercised a loop through the string to replace each character with a decimal entity. Are you wondering how the decimal entities translate to readable characters and vica versa? Take a look at the ASCII table and the ASCII to hex converter tool.

How to loop through a string in PHP?

There is one very nice function in PHP called str_split(). This function converts a string into an array by feeding every single character in the string into its own key => value pair which you can then use in a way that you loop through individual keys and values of the array and do whatever you like with the key => value pairs. The following code shows the syntax of the str_split() function.

array str_split ( string $string [, int $split_length ] )

And now, let's take a look at an example.

$array = str_split($stringEmailAddress);
foreach($array as $char) {
 /* now you do whatever you like with every character of your string */
 /* the following code converts your email address into dec entities */
 $stringEmailAddressConverted .= "&#".ord($char).";";
}

There can be a problem with this function.

Fatal error: Call to undefined function: str_split()

This can happen; when executing the code above, you may run into the Fatal error: Call to undefined function: str_split() error message. You get this message if you run PHP version that is less than PHP 5. If you run PHP 4, you will not be able to use the str_split function, and you have to try something else as we describe next.

Loop through string in PHP 4

The str_split() function was not implemented until PHP 5. If your server is running PHP 4, the function will not exist. If that is the case you would use a combination of chunk_split() and explode(). Chunk_split() is used to split a string into smaller chunks which are then separated with end of lines or Windows-style line breaks (\r\n - carriage return and line feed). After the string is split into smaller chunks, you then use function explode() which returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

The following code shows syntax of chunk_split() and explode().

string chunk_split ( string $body [, int $chunklen [, string $end ]] )
array explode ( string $delimiter , string $string [, int $limit ] )

The code below demonstrates how this can be used together.

$array = explode("\r\n",trim(chunk_split($stringEmailAddress,1)));
foreach($array as $char) {
 /* now you do whatever you like with every character of your string */
 /* the following code converts your email address into dec entities */
 $stringEmailAddressConverted .= "&#".ord($char).";";
}

The chunk_split() function splits your joe_smith@example.com email into j\r\no\r\ne\r\n_\r\n... string. This string is then exploded into an array which holds each letter in a separate key - value pair.

loop through PHP string

Now you can loop through the array, apply dec or hex entity conversion mechanism and create a new string holding converted characters.

Do you have more tutorials on PHP?

Yes, we wrote a few more "how to"s related to PHP. Feel free to take a look at the following two pages: PHP display array content and How to check if string contains substring PHP. In addition to the PHP loop through string tutorial, we have a few others that might interest you:

Dec to hex converter
Hex to decimal converter
ASCII to hex converter
ASCII table
RGB color picker

Questions? You can ask in our discussion forum.

.

Discuss this article or this topic in our discussion forum:
(The table bellow shows a list of 8 most recent topics posted in our discussion forum. Visit our discussion forum to see more. It is possible the links below are not related to this page, but you can be certain you will find related posts in the discussion forum. You can post one yourself too.)
Email this article to a friend:
TO: 
FROM: 
2 + 6 - 3 = 
.
How can I link to this web page?

It is easy, just include the code provided below into your HTML code.

<a href="http://www.maxi-pedia.com/PHP+loop+through+string" title="www.Maxi-Pedia.com: PHP loop through string" target="_blank">PHP loop through string</a>
.