CodeIgniter Forums
how to split a string - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: how to split a string (/thread-23485.html)

Pages: 1 2


how to split a string - El Forum - 10-12-2009

[eluser]megabyte[/eluser]
I have tried a bunch of solutions and the only one htat seems to keep the punctuation and html is the CI function word_limiter, but I can't seem to get it to return both parts.

You know how it returns a portion of the string?


Well I want it to return an array including the limit and the remaining part of the string.


anyone help me out please?

I modified word_limiter() to this:

Code:
function split_content($str)
    {
        
        echo str_word_count($str);
        
        $limit = str_word_count($str) / 2;
        
        echo $limit;
        
        if (trim($str) == '')
        {
            return $str;
        }
    
        preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $match);
        
        $matches[0] = $match[0];
        $matches[1] = str_replace($matches[0], '', $str);
        
        return $matches;
    }


but there must be a better way


how to split a string - El Forum - 10-12-2009

[eluser]jedd[/eluser]
[quote author="megabyte" date="1255411624"]
You know how it returns a portion of the string?

Well I want it to return an array including the limit and the remaining part of the string.
[/quote]

I don't know how it returns a portion of the string - perhaps you could describe it better.

What is the limiting algorithm that you're talking about? Can you give an example of the input and output you're looking for?


how to split a string - El Forum - 10-12-2009

[eluser]megabyte[/eluser]
I updated my post for you.


how to split a string - El Forum - 10-12-2009

[eluser]ShoeLace1291[/eluser]
Maybe you could do something like this:

Code:
$string = "foobar";
$limit = 3;
$length = strlen($string);
if($length > $limit){
    $firsthalf = substr($string, 0, $limit - 1); //parameters are string, start int, end int, so 0 would be the first character and the last character would be 2 in this case
    $secondhalf = substr($string, $limit, $length - 1);
    echo $firsthalf."-".$secondhalf;
    echo $string;
} else {
    echo $string;
}

would produce something like foo-bar


how to split a string - El Forum - 10-12-2009

[eluser]jedd[/eluser]
Call me old fashioned ... but I still think this would be much easier if you described (exactly) what you wanted to do, rather than provide code that doesn't do what you want to do.

If the string is empty, you want it to return an empty string? If so, why not do that test first?

I suspect this would be a really simple function involving an explode, but it's hard to say from here.


how to split a string - El Forum - 10-12-2009

[eluser]megabyte[/eluser]
OK, from the beginning

-take row from db which is a page of text.
- this text was placed in their from a form textarea.
- I then use nl2br, then format text to paragraphs using a function I created below.
- I then want to split the html into 2 equal parts so that I can have 2 equal columns on a webpage like in a newspaper.

Code:
function nl2p($string)
{
    $string = nl2br($string);
    $array = explode('<br />', $string);
    
    $out = '';
    
    foreach($array as $val)
    {
        $out .= '<p>'.$val.'</p>';
        $out .= "\n";
    }
    return $out;
}



how to split a string - El Forum - 10-12-2009

[eluser]jedd[/eluser]
[quote author="megabyte" date="1255413682"]OK, from the beginning
[/quote]

Tremendous idea!

Quote:-take row from db which is a page of text.
- this text was placed in their from a form textarea.
- I then use nl2br, then format text to paragraphs using a function I created below.

Try not to fall into the trap of describing how to do something .. when you're asking the question of how to do something. Describe outcomes!

Quote:- I then want to split the html into 2 equal parts so that I can have 2 equal columns on a webpage like in a newspaper.

I feel we're getting close! Wink

How about this algorithm:

Calculate length of the string.
Identify mid-point.
Search forward from that mid-point until you hit a space.
Split the string at that position.


how to split a string - El Forum - 10-12-2009

[eluser]megabyte[/eluser]
Code:
$length = strlen($str);
$offset = $length/2;
$pos = strpos($str, ' ', $offset);
$first = substr($str, 0, $pos);
$last = substr($str, $pos);
echo $first;
echo "<br />";
echo $last;


Well you helped me solve it in 3 minutes vs the 3 hours i spent not solving it. thanks.


how to split a string - El Forum - 10-12-2009

[eluser]megabyte[/eluser]
now not to make you do any work, but if you wanted to give me a version that splits it in half by word count instead of character count......

Tongue


how to split a string - El Forum - 10-13-2009

[eluser]jedd[/eluser]
To answer the question (subsequently edited, I'm happy to see) in your penultimate post -- I wanted to give you an algorithm so you could more easily identify if that was what you were after. I was having quite some trouble working out your goal here, and rather than produce code in response to your code, and dancing the night away in that fashion, I thought it easier to ... well, in any case, I'm glad that you got it going in three minutes.

[quote author="megabyte" date="1255416801"]now not to make you do any work, but if you wanted to give me a version that splits it in half by word count instead of character count......[/quote]

You make it sound like I'm the one that wants something done! Wink

Here's the result of my boredom.

You are likely going to be able to improve on this, especially if you loiter around the contrib-section of the php.net documentation pages for the functions I've used (and others). There's a bunch of very powerful manipulative functions that I never knew existed.

As you'll see in the output (below) you probably don't want a string split by word count - it is less likely to look normal than one split by string length and then broken at the next space. I accept that my demonstration string is heavily loaded to the left, but nonetheless, I still think strpos() is likely to look better, more often.

Finally, obviously methods 2 and 3 are functionally identical, but the difference you see on odd-numbered word counts can be removed with the judicious usage of a floor() function in there somewhere. I'll leave it to you to work out which one you prefer - I suspect the performance delta is trivial, though the third probably uses a touch more memory. Depends on the frequency of usage, and the sizes of your data, whether you'd notice any difference.


Code:
&lt;?php
    $in_string = "Consider sentences commencifying with extraordinarily gratuitous grandiloquisms such as the type you might find on these forums.";

    echo "<b>". $in_string ."</b>";

    echo "<hr />";

    $result = split_by_size($in_string);
    echo $result['first'];
    echo "<br />";
    echo $result['second'];

    echo "<hr />";

    $result = split_by_word_count ($in_string);
    echo $result['first'];
    echo "<br />";
    echo $result['second'];

    echo "<hr />";

    $result = split_by_array ($in_string);
    echo $result['first'];
    echo "<br />";
    echo $result['second'];



    function split_by_size ($in_string)  {
        $result = array();

        $best_space = strpos ($in_string, " ", (strlen($in_string) / 2));
        $result['first'] = substr ($in_string, 0, $best_space);
        $result['second'] = ltrim (substr ($in_string, $best_space) );

        return $result;
        }


    function split_by_word_count ($in_string)  {
        $result = array();

        $middle_word = substr_count ($in_string, " ") / 2;

        $x = 0;
        $words_found = 0;
        $are_we_there_yet = FALSE;

        while ($are_we_there_yet == FALSE)  {
            if ($in_string[$x] == " ")
                $words_found++;

            if ($words_found >  $middle_word)
                $are_we_there_yet = TRUE;
            
            $x++;
            }

        $result['first']  = substr ($in_string, 0, $x);
        $result['second'] = substr ($in_string, $x);

        return $result;
        }


    function split_by_array ($in_string)  {
        $result = array ();

        $word_array = explode (" ", trim($in_string));
        $mid_by_word = sizeof ($word_array) / 2;

        $result['first']  = implode ( " ", array_slice ($word_array, 0, $mid_by_word) );
        $result['second'] = implode ( " ", array_slice ($word_array, $mid_by_word) );

        return $result;
        }


Output:
Code:
Consider sentences commencifying with extraordinarily gratuitous grandiloquisms such as the type you might find on these forums.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -

Consider sentences commencifying with extraordinarily gratuitous
grandiloquisms such as the type you might find on these forums.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -

Consider sentences commencifying with extraordinarily gratuitous grandiloquisms such as
the type you might find on these forums.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -

Consider sentences commencifying with extraordinarily gratuitous grandiloquisms such
as the type you might find on these forums.