如何用php拆分字符串

时间:2022-01-01 01:59:06

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 ;)

当然我可以使用爆炸两次,但我相信这不是最好的解决方案;)

4 个解决方案

#1


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

如果你想分成几个不同的字符,请看看preg_split

//split string on space or period:
$split=preg_split('/[ \.]/', $string);

#2


There's string token strtok.

有字符串标记strtok。

#3


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

你想要strtok功能。手册给出了这个例子:

<?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.

虽然在你的情况下,我怀疑使用爆炸两次更容易,看起来更好。

#4


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

你可以做一个。进入太空然后被太空爆炸。因为strtr非常快。

#1


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

如果你想分成几个不同的字符,请看看preg_split

//split string on space or period:
$split=preg_split('/[ \.]/', $string);

#2


There's string token strtok.

有字符串标记strtok。

#3


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

你想要strtok功能。手册给出了这个例子:

<?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.

虽然在你的情况下,我怀疑使用爆炸两次更容易,看起来更好。

#4


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

你可以做一个。进入太空然后被太空爆炸。因为strtr非常快。