tags:

views:

51

answers:

3

If I have a string of characters like so:

This is a test string and I wa

And I wanted to delete everything after the "I" which would also include the space after the I, how would I do this? I definitely need to start at the end of the string and count backwards to the last space but I'm not sure how to do this.

+1  A: 

Use this to find the last occurence of a character in a string

http://www.php.net/manual/en/function.strrpos.php

$pos = strrpos($mystring, "I");

Then substr to split the string

http://ca2.php.net/manual/en/function.substr.php

$newstring = substr($mystring, $pos);
Chad
Thanks Chad, I'll have a look there now.
Jim
@Jim, I added the method to split it once you find the location of the "I"
Chad
Thanks Chad. The string will, however be dynamic. I'm not sure I can use strpos for this.
Jim
Oh, I reread your comments and see that your requirements are to cut off incomplete words... not sure how you're going to know that "I want to go with the" is the incomplete sentence of "I want to go with them" though?
Chad
+2  A: 

You can remove everything after the 'I' by using:

$str = 'This is a test string and I wa';
$new_string = substr($str, 0, strpos($str, 'I') + 1);

Note: strpos finds the first occurrence of the 'I' character.

Tim Cooper
Use strrpos to find last occurence if you want that instead.That will be: `$str = 'This is a test string and I wa'; $new_string = substr($str, 0, strrpos($str, 'I') + 1);`
Emil
A: 

You're requirement is not really clear... but

if you want to delete everything after the 'I'

$s = 'This is a test string and I wa';
$pos = strpos($s, 'I');
if ($pos !== false)
{
   $s = substr($s, 0, $pos + 1);
}

if you want to remove the last space and everything after if

$s = 'This is a test string and I wa';
$pos = strrpos($s, ' ');
if ($pos !== false)
{
   $s = substr($s, 0, $pos);
}
t00ny