単語を文字列から分割します。たとえば、私の文字列は "#name of god"であり、 "name"だけが必要です! しかし、私はこのsnipetを使用する場合、 "神の名を" 私を返すPHP - 特定の単語を文字列で分解して分割します。
$string = "In the #name of god";
$word = explode('#', $string);
echo $word;
単語を文字列から分割します。たとえば、私の文字列は "#name of god"であり、 "name"だけが必要です! しかし、私はこの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は、文字列を配列に変換します。 あなたの出力は["In"、 "神の名前"]になります。あなたがそれについての言葉をキャッチしたいのであれば、それがどのように機能するかについてより具体的にする必要があります。ハッシュタグの後に最初の単語をキャッチする場合は、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));
}
これは間違いなく 'name'を返しません。 –
Ops、私は本当にその部分を逃しました。私はそれに取り組んでいます。 –
@ Daaanが修正しました。 –
トライ正規表現と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'は配列です。エコーすると'神の名前 ' –
が表示されます。間違ったコンテキストでここにエクスポートしています。 'explode()'関数は文字列を配列に分割します。 – webpic
@u_mulder、Array([0] =>神の[1] =>の名前で) – Ehsan