【问题标题】:Custom PHP tagging system assistance, finding username自定义 PHP 标记系统帮助,查找用户名
【发布时间】:2014-12-10 21:53:00
【问题描述】:

我目前正在我网站的个人资料页面中制作标签系统。如果用户指定:+tag[username],其中 username 等于该人的好友用户名,它将 preg_replace 将标签替换为指向用户的链接。使用 strpos 查找 +tag 很容易,但我要问的问题是如何将用户名作为变量提取。例如:如果 $text = '嘿 +tag[matty] 你好吗!'

if (strpos($text, '+tag[//username//]' !== false)) {
//get //username// and store as $username
} 

让它看起来像这样:

if (strpos($text '+tag[//username//]' !== false) {
   $username = "matty";
}

感谢所有提前回复的人:)

【问题讨论】:

    标签: php html tags system


    【解决方案1】:

    使用正则表达式匹配函数preg_match怎么样?

    $subject = "hey +tag[matty] how are you!";
    $pattern = '/\+tag\[(.*?)\]/';
    preg_match($pattern, $subject, $matches);
    $username = $matches[1];
    echo $username;
    

    要匹配标签的多个实例,您需要使用preg_match_all

    $subject = "Hey +tag[matty]! Want to meet up with +tag[keshia] later?";
    $pattern = '/\+tag\[(.*?)\]/';
    preg_match_all($pattern, $subject, $matches);
    foreach($matches[1] as $username){
        echo $username.'<br>';
    }
    

    【讨论】:

    • 嘿,格伦,感谢您的快速回复,就此而言,PREG_OFFSET_CAPTURE 是做什么的?再次感谢
    • 来自 php.net:PREG_OFFSET_CAPTURE If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the value of matches into an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.
    • 对于您的用例,实际上可能没有必要。我已经修改了我的代码以不使用该标志。如果你很好奇,它会抓取匹配的字符串偏移量。
    • 非常感谢你们,真的非常感谢:)
    • 我还有一个小问题要问是否可以。您如何使用此代码检测 +tag[//username] 的多次出现并将它们存储在数组中?感谢所有帮助。到目前为止,我已经用 '$amount = substr_count($content, '+tag[');' 计算了出现次数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多