我想从字符串拆分单词。例如,我的字符串是“在上帝的#名称”,我只需要“名称”! 但是当我使用这个snipet,还给我 “上帝的名字”Php - 通过在字符串中爆炸拆分特定字
$string = "In the #name of god";
$word = explode('#', $string);
echo $word;
我想从字符串拆分单词。例如,我的字符串是“在上帝的#名称”,我只需要“名称”! 但是当我使用这个snipet,还给我 “上帝的名字”Php - 通过在字符串中爆炸拆分特定字
$string = "In the #name of god";
$word = explode('#', $string);
echo $word;
$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'
注:
reset
函数之前@
字符是Error Control Operators。当使用带有非参考变量的end
函数时,它避免显示警告消息,并且是的,这是不好的做法。您应该创建自己的变量并传递给end
函数。就像这样:
// Using `explode`
$segments = explode('#', $string);
$segments = explode(' ', end($segments));
$word = reset($segments);
echo $word; // 'name'
对不起,我只是readed是错误的。
Explode将字符串转换为数组。 所以你的输出会导致[“在”,“神的名字”]。如果你想听到它的话,你需要更具体地说明它如何工作。如果你只想要在标签后面看到第一个单词,你应该使用strpos和substr。
$string = "In the #name of god";
$hashtag_pos = strpos($string, "#");
if($hashtag_pos === false)
echo ""; // hashtag not found
else {
$last_whitespace_after_hashtag = strpos($string, " ", $hashtag_pos);
$len = $last_whitespace_after_hashtag === false ? strlen($string)-($hashtag_pos+1) : $last_whitespace_after_hashtag - ($hashtag_pos+1);
echo substr($string, $hashtag_pos+1, strpos($string, " ", $len));
}
这绝对不会返回'名称' –
行动,我真的错过了那部分。我在做这个工作。 –
@Daan修复它。 –
尝试正则表达式和preg_match
$string = "In the #name of god";
preg_match('/(?<=#)\w+/', $string, $matches);
print_r($matches);
输出:
Array ([0] => name)
这也返回一个数组?在 – RiggsFolly
这个问题中请求了一个字符串@RiggsFolly是的,但'$ matches [0]'将会有必需的字符串,并且复杂度非常小。 –
也会建议使用'preg_match_all'来获得所有的发生 – knetsi
有几个选项(还的preg_match将有助于为 '#' 的多个实例)
<?php
//With Explode only (meh)
$sen = "In the #name of god";
$w = explode(' ', explode('#',$sen)[1])[0];
echo $w;
//With substr and strpos
$s = strpos($sen , '#')+1; // find where # is
$e = strpos(substr($sen, $s), ' ')+1; //find i
$w = substr($sen, $s, $e);
echo $w;
//with substr, strpos and explode
$w = explode(' ', substr($sen, strpos($sen , '#')+1))[0];
echo $w;
'$ word'是数组,当您回显它时,您将看不到'name of god' –
您正在使用导出错误的上下文。 'explode()'函数将一个字符串分解成一个数组。 – webpic
@u_mulder,Array([0] =>在[1] =>上帝的名字) – Ehsan