Reputation: 20726
How can I get the substring before the first space or dot?
Like
$string = "test.test"
//result = test
$string = "test doe"
//result = test
Sure I can use explode two times, but I am sure that's not the best solutions.
Upvotes: 9
Views: 17202
Reputation: 96159
You can use strtok()
and offer the two characters as its character mask parameter:
foreach (array("test.test", "test doe") as $string) {
echo strtok($string, " ."), " \n";
}
// test
// test
Upvotes: 1
Reputation: 300865
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);
Upvotes: 14
Reputation: 73778
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.
Upvotes: 2
Reputation: 70001
You could do a strtr of . into space and then explode by space. Since strtr is very fast.
Upvotes: 0