2014-12-10 124 views
0

我目前正在我的网站的个人资料页面内制作标签系统。如果用户指定:+tag[username]其中用户名等于该用户的朋友所使用的用户名,它将preg_replace与该用户的链接的标记。使用strpos查找+标签很容易,但我所问的问题是如何将用户名作为变量。例如:if $ text ='hey + tag [matty]你好吗?'自定义PHP标记系统的帮助,找到用户名

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

,使其看起来像这样:

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

三江源所有谁提前:)

回答

3

有关使用正则表达式匹配功能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>'; 
} 
+0

嘿幽谷,快速回复感谢,在这方面是什么PREG_OFFSET_CAPTURE办?再次感谢 – MyiWorld 2014-12-10 21:59:40

+0

来自php.net:'PREG_OFFSET_CAPTURE 如果这个标志被传递,对于每一个发生的匹配,附属的字符串偏移量也将被返回。请注意,这会将匹配值更改为一个数组,其中每个元素都是由偏移量为0的匹配字符串组成的数组,并且其偏移量为偏移量为1的字符串。 – 2014-12-10 22:01:28

+0

对于您的用例,实际上可能并不需要。我修改了我的代码,不使用该标志。如果你好奇,它会抓取匹配的字符串偏移量。 – Glen 2014-12-10 22:01:54