Splitting a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Splitting a string

Post by impulse() »

I should probably know the answer to this, but it's not apparent at the moment.

I I had a string like this - "hellomynameisstephen". How would it be possible to split it by each letter separately? So there are as many elements as there are letters.

Regards,
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

Code: Select all

$array = str_split('hellomynameisstephen');
Only works in php5... I'm curious to find a php4 solution, will keep looking.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

Here's a php4 version of str_split():

Code: Select all

function str_split($str) {
	$output = array();
	for($i=0;$i<strlen($str);$i++){
		$output[] = $str{$i};
	}
	return $output;
}
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Code: Select all

chunk_split($str, 1, '');
Is possibly a better php 4 solution.
brendandonhue
Forum Commoner
Posts: 71
Joined: Mon Sep 25, 2006 3:21 pm

Post by brendandonhue »

You can access a string as if it were an array in PHP, if that works for what you're trying to do.
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Post by impulse() »

I needed to use a

Code: Select all

foreach
statement. And that doesn't seem to recognise a string as an array nor does

Code: Select all

count
so I was unable to define how many times the loop should occur.
brendandonhue
Forum Commoner
Posts: 71
Joined: Mon Sep 25, 2006 3:21 pm

Post by brendandonhue »

Code: Select all

<?php
$string = 'hellomynameisstephen';
$length = strlen($string);
for($i = 0; $i < $length; $i++)
{
  echo $string[$i] . '<br>';
}
?>
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

ole wrote:

Code: Select all

chunk_split($str, 1, '');
Is possibly a better php 4 solution.
Looked at that one, outputs a string :wink:

You could just include the function wrapped in a condition:

Code: Select all

if(!function_exists('str_split')){
	function str_split($str) {
		$output = array();
		for($i=0;$i<strlen($str);$i++){
			$output[] = $str{$i};
		}
		return $output;
	}
}
That way it will be defined as a replacement for the native php5 str_split() if it doesn't already exist.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Looked at that one, outputs a string
Ahh sorry. I didn't test it. Although I will now because I'm puzzling over exactly what that function is supposed to do.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

OK here is the most comprehensive replacement for str_split() I could come up with:

Code: Select all

if (!function_exists('str_split')) {
    /**
     * PHP 4 equivlent of str_split.
     *
     * @link http://php.net/manual/en/reference.pcre ... ifiers.php
     *       for utf8 availability
     * @param string $string
     * @param int $length
     * @param bool $utf8Support
     * @return array
     */
    function str_split($string, $length = 1, $utf8Support = false)
    {
        if (!$length || !is_int($length)) {
            return $string;
        }
        $pattern = '~(.{' . $length. '})~s' . ($utf8Support ? 'u' : '');
        return array_values(array_filter(
            preg_split($pattern, $string, null, PREG_SPLIT_DELIM_CAPTURE)
        ));
    }
}
function test($actual, $expected)
{
    if ($actual == $expected) {
        return;
    }
    echo '<pre>', var_dump($actual, true), '</pre><br />';
}
test(str_split('foo'), array('f', 'o', 'o'));
test(str_split("\r\n\t"), array("\r", "\n", "\t"));
test(str_split('foo', 2), array('fo', 'o'));
the array_values(array_filter( is necessary because preg_split returns a load of empty elements and the PREG_SPLIT_NO_EMPTY flag causes it to return nothing. I'm interested if anyone has a better solution to that. I haven't tested performance of this but it not impossible it will out perform the for loop version.

and for anyone who is wondering chunk_split pads adds spaces (or other char) every nth char.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

ole wrote:
Looked at that one, outputs a string
Ahh sorry. I didn't test it. Although I will now because I'm puzzling over exactly what that function is supposed to do.
It will inject a character into a string after so many characters... it's often used to add line breaks (\r\n) to a long string, like base64'd data in an email.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

You know, there is str_split() in the PEAR compatibility library.

http://pear.php.net/package/PHP_Compat
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

You know, there is str_split() in the PEAR compatibility library.
Why didn't you say so before! Tiiskk Honestly.
OK there's is better

Code: Select all

if (!function_exists('str_split')) {
    function str_split($string, $split_length = 1)
    {
        if (!is_scalar($split_length)) {
            user_error('str_split() expects parameter 2 to be long, ' .
                gettype($split_length) . ' given', E_USER_WARNING);
            return false;
        }

        $split_length = (int) $split_length;
        if ($split_length < 1) {
            user_error('str_split() The length of each segment must be greater than zero', E_USER_WARNING);
            return false;
        }
        
        // Select split method
        if ($split_length < 65536) {
            // Faster, but only works for less than 2^16
            preg_match_all('/.{1,' . $split_length . '}/s', $string, $matches);
            return $matches[0];
        } else {
            // Required due to preg limitations
            $arr = array();
            $idx = 0;
            $pos = 0;
            $len = strlen($string);

            while ($len > 0) {
                $blk = ($len < $split_length) ? $len : $split_length;
                $arr[$idx++] = substr($string, $pos, $blk);
                $pos += $blk;
                $len -= $blk;
            }

            return $arr;
        }
    }
}
They used preg_match_all.
Post Reply