Jump to content

Recommended Posts

Hello everyone  ;D

 

I went to the php.net site for the substr function and found a script that allows you to set a delimiter between to points.

 

What I need to do, and I don't know is this is possible, is to set the delimiter as the second period in the string.

 

EXAMPLE

 

$string = Hello everyone. Welcome to class. I hope you're all smart enough not to be dumb.

 

DESIRED OUTPUT

 

echo $string

//Hello everyone. Welcome to class.

 

Does anyone know if this is possible to do with or without the substr function?

 

Thanks for the help!

How about:

 

<?php
function stringDelim($string, $delim, $count) {
$lastPos = 0;
$delimCount = 0;
for ($i = 0; $i < $count; $i++) {
	if (!strpos($string, $delim, $lastPos)) break;
	else {
		$lastPos = strpos($string, $delim, $lastPos + 1) + 1;
		$delimCount++;
	}
}
if ($delimCount < $count) return $string;
else return substr($string, 0, $lastPos);
}
print stringDelim("Hello everyone. Welcome to class. I hope you're all smart enough not to be dumb.", ".", 2);
?>

Tested and working under PHP 5.  Its pretty self explanatory.  If it doesn't find a second delimiter, it returns the whole string, same if it finds none at all.  If it finds 2 or more, it returns the string up until the second.  I made it into a function so you can use whatever delimiter and count you with to use.

$str = 'Hello everyone. Welcome to class. I hope you\'re all smart enough not to be dumb.';
$str_pieces = explode('.', $str);
$str_pieces = array_slice($str_pieces, 0, 2);
$new_str = join('.', $str_pieces) . '.';
print "$str => $new_str\n";

 

That's the explode/join technique.  You can also use regular expressions.

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.