0

文字列に # を持つ単語があるたびに、その単語を配列に保存したいのですが、ここに私のコードがあります:

<?php
function tag($matches)
{
    $hash_tag = array();
    $hash_tag[]=$matches[1];
    return '<strong>' . $matches[1] . '</strong>';
}
$test = 'this is a #test1 #test2 #test3 #test4 #test5 #test6';
$regex = "#(\#.+)#";
$test = preg_replace_callback($regex, "tag", $test);
echo $test;
?>

しかし、新しい単語を配列 $hash_tag の新しいセルに入れる方法がわかりません。これについて本当に助けが必要です

4

4 に答える 4

1

同時に2つのことをしたいことがわかります

  • 単語を強力なタグに置き換えます
  • 後で使用するすべての単語を取得する

あなたが試すことができます

$hash_tag = array();
$tag = function ($matches) use(&$hash_tag) {
    $hash_tag[] = $matches[1];
    return '<strong>' . $matches[1] . '</strong>';
};

$test = 'this is a #test1 #test2 #test3 #test4 #test5 #test6';
$regex = "/(\#[0-9a-z]+)/i";
$test = preg_replace_callback($regex, $tag, $test);
echo $test;
var_dump($hash_tag); <------ all words now in this array 

出力

これは#test1 #test2 #test3 #test4 #test5 #test6 です

array (size=6)
  0 => string '#test1' (length=6)
  1 => string '#test2' (length=6)
  2 => string '#test3' (length=6)
  3 => string '#test4' (length=6)
  4 => string '#test5' (length=6)
  5 => string '#test6' (length=6)
于 2012-11-11T22:29:05.697 に答える
1

preg_match_all ()を使用してみてください

1 つの配列ですべての一致を取得した後、それをループすることができます。

于 2012-11-11T22:25:19.823 に答える
0

すべての一致を使用preg_match_all()してループします。

<?php
$test = 'this is a #test1 #test2 #test3 #test4 #test5 #test6';
$regex = "(\#[^#]+?)";
preg_match_all($regex, $test, $hash_tag);
foreach ($hash_tag as $match) {
    echo '<strong>' . $match . '</strong>';
}
?>
于 2012-11-11T22:28:34.407 に答える
0

さて、正規表現は次のとおりです。/\#[a-zA-Z0-9]*/

PHPでは、私はあなたが使用すると信じていますpreg_match_all('/\#[a-zA-Z0-9]*/', string)

于 2012-11-11T22:27:49.460 に答える