johnnnnny
johnnnnny

Reputation:

How to remove the rest of a string

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

Upvotes: 0

Views: 1539

Answers (4)

ghostdog74
ghostdog74

Reputation: 342273

$somestring="Hello - Bye";
$array=preg_split("/\s+-\s+/",$somestring,2);
print $array[0]."\n";

Upvotes: 0

cletus
cletus

Reputation: 625007

$str = preg_replace('!-.*$!', '', 'Hello - Byte');

Upvotes: 1

Gumbo
Gumbo

Reputation: 655129

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.

Upvotes: 6

Anti Veeranna
Anti Veeranna

Reputation: 11583

$pieces = explode('-', 'Hello - Bye', 2);
print $pieces[0];

Upvotes: 2

Related Questions