homelessDevOps
homelessDevOps

Reputation: 20726

Isolate leading string before one of two delimiting characters

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

Answers (5)

VolkerK
VolkerK

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

Paul Dixon
Paul Dixon

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

Martin Geisler
Martin Geisler

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

Mario
Mario

Reputation: 1525

There's string token strtok.

Upvotes: 2

&#211;lafur Waage
&#211;lafur Waage

Reputation: 70001

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

Upvotes: 0

Related Questions