开发者

How to delete part of a string

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 t开发者_JAVA技巧he end of the string and count backwards to the last space but I'm not sure how to do this.


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.


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);


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜