tags:

views:

1196

answers:

5

Hi ,

is there any nice way to split an string after " " or . ?

Like

$string = "test.test" result = test

$string = "test doe" result = test

Sure i can use explode two times, but I am sure thats not the best solutions ;)

+11  A: 

If you want to split on several different chars, take a look at preg_split

//split string on space or period:
$split=preg_split('/[ \.]/', $string);
Paul Dixon
eek, well spotted
Paul Dixon
works fine, thanks a lot
ArneRie
+1  A: 

You could do a strtr of . into space and then explode by space. Since strtr is very fast.

Ólafur Waage
+3  A: 

There's string token strtok.

Mario
+3  A: 

You want the strtok function. The manual gives this example:

<?php
$string = "This is\tan example\nstring";
/* Use tab and newline as tokenizing characters as well  */
$tok = strtok($string, " \n\t");

while ($tok !== false) {
    echo "Word=$tok<br />";
    $tok = strtok(" \n\t");
}
?>

Though in your case I suspect that using explode twice is easier and looks better.

Martin Geisler
A: 

I agree with Ólafur Waage, strstr is much faster when compared with a regular expression like preg_split.