views:

137

answers:

4

If i have a string like so:

Hello - Bye

How can i make php find and delete a specifc character and the rest of the string on wards

like an example

Hello - Bye

find the character -

and be left with the string

Hello

+5  A: 

Use strpos to find the position of the first occurence of a substring and then substr to just get everything up to that position:

$pos = strpos($str, '-');
if ($pos !== false) {  // strpos returns false if there is no needle in the haystack
    $str = substr($str, 0, $pos);
}

And if you have PHP 5.3 and later, you could also use the strstr function with the third parameter set to true.

Gumbo
if your string has more then one hyphen in it, you could also use strrpos, to get the last matching occurrence of the the specified character, depending on your requirements
bumperbox
Damn, wish I could upvote you again for the extra bit of info about 5.3, very interesting :)
xenon
+1  A: 
$pieces = explode('-', 'Hello - Bye', 2);
print $pieces[0];
Anti Veeranna
+1  A: 
$str = preg_replace('!-.*$!', '', 'Hello - Byte');
cletus
A: 
$somestring="Hello - Bye";
$array=preg_split("/\s+-\s+/",$somestring,2);
print $array[0]."\n";