doufei3152 2012-11-11 22:21
浏览 57
已采纳

正则表达式,保存数组中的值

In a string each time there is a word with a # I want to save the word in an array, here my code :

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

But I don't know how to put each new word in a new cell of the array $hash_tag and i really need help on this one

  • 写回答

4条回答 默认 最新

  • dongyanju1094 2012-11-11 22:29
    关注

    I can see you want to do 2 things at the same time

    • Replace the words with strong tag
    • Get all the words ans use later

    You can try

    $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 
    

    Output

    this is a #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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?