Jump to content

String Help


dennismonsewicz

Recommended Posts

The way that question is worded is a bit odd.

 

PHP will handle a string as simply that...a string.  There is no "next character" in a string, because PHP looks at the string as a whole.

 

The poster above me hit the nail on the head, you will need to split your string up into multiple parts and have PHP parse it that way.

 

Good luck!

Link to comment
Share on other sites

The way that question is worded is a bit odd.

 

PHP will handle a string as simply that...a string.  There is no "next character" in a string, because PHP looks at the string as a whole.

 

The poster above me hit the nail on the head, you will need to split your string up into multiple parts and have PHP parse it that way.

 

Good luck!

 

Well I am trying to write a script that takes a string and splits it after a certain amount of characters but if the split occurs in a word then do not split until the next whitespace.

Link to comment
Share on other sites

look at php's wordwrap function

 

http://php.net/manual/en/function.wordwrap.php

 

I tried the above function but for some reason its not working :(

 

<?php

$str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eros elit, viverra vitae aliquet sed, suscipit aliquet sapien. Vivamus semper augue nec tellus condimentum consectetur dignissim turpis egestas.";
$brk = wordwrap($str, 34, "\n");
echo $brk;

?>

Link to comment
Share on other sites

look at php's wordwrap function

 

http://php.net/manual/en/function.wordwrap.php

 

I tried the above function but for some reason its not working :(

 

<?php

$str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eros elit, viverra vitae aliquet sed, suscipit aliquet sapien. Vivamus semper augue nec tellus condimentum consectetur dignissim turpis egestas.";
$brk = wordwrap($str, 34, "\n");
echo $brk;

?>

 

It should be.  If you're viewing it in a browser, it isn't going to make returns with \n.  It'll make them with something like <br />.  If you look at the output HTML, you should see that the string has been broken up as you've specified, only the line breaks are being ignored by the browser when rendered.

Link to comment
Share on other sites

look at php's wordwrap function

 

http://php.net/manual/en/function.wordwrap.php

 

I tried the above function but for some reason its not working :(

 

<?php

$str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eros elit, viverra vitae aliquet sed, suscipit aliquet sapien. Vivamus semper augue nec tellus condimentum consectetur dignissim turpis egestas.";
$brk = wordwrap($str, 34, "\n");
echo $brk;

?>

 

It should be.  If you're viewing it in a browser, it isn't going to make returns with \n.  It'll make them with something like <br />.  If you look at the output HTML, you should see that the string has been broken up as you've specified, only the line breaks are being ignored by the browser when rendered.

 

OOOO! Its working now! Thanks!

Link to comment
Share on other sites

If you are trying to wrap words to prevent breaking tables, i actually just dealt with this issue on one of my projects. It may sound counter-intuitive at first, but heres how I solved it.

 

i used CSS to style the table, and do the word wrapping on the client side.

 

I did this for several reasons:

1. helps maintain copy/paste of the field. So if the browser deals with the word-wrapping, when the content is copied and pasted elsewhere, it will maintain the content on a single line

2. it is less server intensive, and has performance implications. If you add 1 line per code, in a loop with 50,000 instances, you effectively added 50,000 lines of code to your application, and this can affect performance.

3. Its semantically correct. use css to control style.

 

If your interested in this type of solution, you can explore the table-layout, word-wrap, work-break, and possibly clear properties.

Link to comment
Share on other sites

So I have been battling with this all afternoon on how to write this script and have the following:

 

$limit = 45;
$firstpart = substr($array['details'], 0, $limit);
$secondpart = substr($array['details'], $limit);

 

Now I tried several solutions before reverting back to the above (the original solution)... the problem with the above solution is that it will break in the middle, beginning or end of a word and place the rest of that word in the $secondpart variable... how could I tell if there is a whole word before breaking? I am completely lost as to how to do this.

 

Thanks in advance!

Dennis

Link to comment
Share on other sites

Sometimes, the best thing to do is to look through the manual.

 

http://us3.php.net/manual/en/function.substr.php#73233

 

 ijavier aka(not imatech) igjav
14-Feb-2007 10:20
<?php
/*
    An advanced substr but without breaking words in the middle.
    Comes in 3 flavours, one gets up to length chars as a maximum, the other with length chars as a minimum up to the next word, and the other considers removing final dots, commas and etcteteras for the sake of beauty (hahaha).
   This functions were posted by me some years ago, in the middle of the ages I had to use them in some corporations incorporated, with the luck to find them in some php not up to date mirrors. These mirrors are rarely being more not up to date till the end of the world... Well, may be am I the only person that finds usef not t bre word in th middl?

Than! (ks)

This is the calling syntax:

    snippet(phrase,[max length],[phrase tail])
    snippetgreedy(phrase,[max length before next space],[phrase tail])

*/

function snippet($text,$length=64,$tail="...") {
    $text = trim($text);
    $txtl = strlen($text);
    if($txtl > $length) {
        for($i=1;$text[$length-$i]!=" ";$i++) {
            if($i == $length) {
                return substr($text,0,$length) . $tail;
            }
        }
        $text = substr($text,0,$length-$i+1) . $tail;
    }
    return $text;
}

// It behaves greedy, gets length characters ore goes for more

function snippetgreedy($text,$length=64,$tail="...") {
    $text = trim($text);
    if(strlen($text) > $length) {
        for($i=0;$text[$length+$i]!=" ";$i++) {
            if(!$text[$length+$i]) {
                return $text;
            }
        }
        $text = substr($text,0,$length+$i) . $tail;
    }
    return $text;
}

// The same as the snippet but removing latest low punctuation chars,
// if they exist (dots and commas). It performs a later suffixal trim of spaces

function snippetwop($text,$length=64,$tail="...") {
    $text = trim($text);
    $txtl = strlen($text);
    if($txtl > $length) {
        for($i=1;$text[$length-$i]!=" ";$i++) {
            if($i == $length) {
                return substr($text,0,$length) . $tail;
            }
        }
        for(;$text[$length-$i]=="," || $text[$length-$i]=="." || $text[$length-$i]==" ";$i++) {;}
        $text = substr($text,0,$length-$i+1) . $tail;
    }
    return $text;
}

/*
echo(snippet("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea") . "<br>");
echo(snippetwop("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea") . "<br>");
echo(snippetgreedy("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea"));
*/
?>

Link to comment
Share on other sites

because I'm in a great mood, I threw this together quickly.  seems to work.  if the dead center is a space, done!  if not, it loops until it finds the nearest spot to the middle moving backwards from the center point.

 

UPDATE: ok I actually read the post and replies and i see you wanted to be able to split it any any location, but it would be really simple to modify my code to do that, and anyhow, should give you an idea of how to go about doing it. good luck =)

 


<?php
$a = 'This is a crazy long string to test this out on where the middle byte is not a space.';
$len = strlen($a);
if ( substr($a, $len/2, 1) == ' ' )
{
$FirstHalf = substr($a, 0, $len/2);
$SecondHalf = substr($a, $len/2);
}
else
{
for ( $i = $len/2; $i > 0; $i-- )
{
	if ( substr($a, $i, 1) == ' ' )
	{
		$FirstHalf = substr($a, 0, $i);
		$SecondHalf = substr($a, $i);
		break;
	}
}
}
echo $FirstHalf . '<br>';
echo $SecondHalf . '<br>';
?>

Link to comment
Share on other sites

because I'm in a great mood, I threw this together quickly.  seems to work.  if the dead center is a space, done!  if not, it loops until it finds the nearest spot to the middle moving backwards from the center point.

 

UPDATE: ok I actually read the post and replies and i see you wanted to be able to split it any any location, but it would be really simple to modify my code to do that, and anyhow, should give you an idea of how to go about doing it. good luck =)

 


<?php
$a = 'This is a crazy long string to test this out on where the middle byte is not a space.';
$len = strlen($a);
if ( substr($a, $len/2, 1) == ' ' )
{
$FirstHalf = substr($a, 0, $len/2);
$SecondHalf = substr($a, $len/2);
}
else
{
for ( $i = $len/2; $i > 0; $i-- )
{
	if ( substr($a, $i, 1) == ' ' )
	{
		$FirstHalf = substr($a, 0, $i);
		$SecondHalf = substr($a, $i);
		break;
	}
}
}
echo $FirstHalf . '<br>';
echo $SecondHalf . '<br>';
?>

 

Thank you SOOO much for this piece of code! I just did some testing on it and it is working perfectly! This is why I love PHP and especially this forum! I just changed everything over to a function

 

function string_into_parts($a) {
$array = array();
$len = strlen($a);
	if ( substr($a, $len/2, 1) == ' ' ) {
		$FirstHalf = substr($a, 0, $len/2);
		$SecondHalf = substr($a, $len/2);
	} else {

	for ( $i = $len/2; $i > 0; $i-- ) {
		if ( substr($a, $i, 1) == ' ' ) {
				$array['firstHalf'] = substr($a, 0, $i);
				$array['secondHalf'] = substr($a, $i);
				break;
			}
		}
	}
	return $array;
}

$a = 'This is a string that is broken up and its awesome! It must be awesome because it is broken up!';

echo '<pre>';
print_r(string_into_parts($a));
echo '</pre>';

Link to comment
Share on other sites

One more question and I will leave you along =)

 

I have a character limit I am passing to the function to try to break the string at the limit, but have no idea to modify your script to break the string at the limit and if the break is in the middle of a word wait to after the limit to make the break... sorry for the confusion :(

 

function string_into_parts($a, $limit = 45) {
$array = array();
$len = strlen($a);
	if ( substr($a, $len/2, 1) == ' ' ) {
		$array['firstHalf'] = substr($a, 0, $limit);
		$array['secondHalf'] = substr($a, $limit);
	} else {
		for ( $i = $len; $i > 0; $i-- ) {
			if ( substr($a, $i, 1) == ' ' ) {
					$array['firstHalf'] = substr($a, 0, $i);
					$array['secondHalf'] = substr($a, $i);
					break;
				}
			}
	}
return $array;
}

$a = 'It blew up!';
$parts = string_into_parts($a);

echo $parts['firstHalf'] . '<br />';
echo $parts['secondHalf'];

 

Thanks for ALL of your help =)

Link to comment
Share on other sites

I figured out my problem =)

 

<?php
function split_into_parts($text,$length=64) {
    $text = trim($text);
$array = array();
    if(strlen($text) > $length) {
        for($i=0;$text[$length+$i]!=" ";$i++) {
            if(!$text[$length+$i]) {
                return $text;
            }
        }
        $array['firstHalf'] = trim(substr($text,0,$length+$i));
	$array['secondHalf'] = trim(substr($text,$length+$i));
    }
    return $array;
}

$a = 'It blew up. It blew up. It blew up. It blew up.';

echo '<div style="width: 500px; margin: 10px; background: #eee; padding: 6px; border: 1px solid #dfdfdf">';
echo '<p><strong>SplitIntoParts()</strong></p>';
echo '<pre>';
	print_r(split_into_parts($a, 45));
echo '</pre>';
echo '</div>';
?>

 

I basically took a function on the php.net website called snippetgreedy and modified it to meet my needs

 

Original Code

function snippetgreedy($text,$length=64,$tail="...") {
    $text = trim($text);
    if(strlen($text) > $length) {
        for($i=0;$text[$length+$i]!=" ";$i++) {
            if(!$text[$length+$i]) {
                return $text;
            }
        }
        $text = substr($text,0,$length+$i) . $tail;
    }
    return $text;
} 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.