Php - 通过在字符串中爆炸来分割特定单词

Ehs*_*san 1 php split explode

我想从字符串中分割单词.例如,我的字符串是"在#name of god"中,我只需要"名字"!! 但是当我使用这个snipet时,请给我"上帝的名字"

$string = "In the #name of god";    
$word   = explode( '#', $string );
echo $word;
Run Code Online (Sandbox Code Playgroud)

Pig*_*all 5

$string = "In the #name of god";

// Using `explode`
$word   = @reset(explode(' ', end(explode( '#', $string ))));
echo $word; // 'name'

// Using `substr`
$pos1 = strpos($string, '#');
$pos2 = strpos($string, ' ', $pos1) - $pos1;
echo substr($string, $pos1 + 1, $pos2);  // 'name'
Run Code Online (Sandbox Code Playgroud)

注意:函数@前面的字符reset错误控制操作符.当使用end带有非引用变量的函数时,它避免显示警告消息,是的,这是一种不好的做法.您应该创建自己的变量并传递给end函数.像这样:

// Using `explode`
$segments = explode( '#', $string );
$segments = explode(' ', end($segments));
$word = reset($segments);
echo $word; // 'name'
Run Code Online (Sandbox Code Playgroud)