Jump to content

Trying to set a delimiter with substr. Possible?


suttercain

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.