简体   繁体   English

如何修改正则表达式以仅匹配字符串中的特定数字?

[英]How to modify a regex to only match a specific number in a string?

Below is my code to replace all mentions with their respective profile links using tag. 以下是我的代码,使用标记将所有提及内容替换为其各自的个人资料链接。

Now what i need is to remove a specific mention from this string. 现在,我需要从此字符串中删除特定的提及。

Say i have string "hi how are you guys???... @@[Sam Thomas:10181] @@[Jack Daniel:11074] " 说我有一个字符串“嗨,你们好吗?……... @@ [萨姆·托马斯(Sam Thomas):10181] @@ [杰克·丹尼尔(Jack Daniel):11074]”

now i want to remove @@[Sam Thomas:10181] from this string using his id which will be unique one ie 10181.. any regular expression to identify this whole pattern using id as specified above. 现在我想使用他的ID从该字符串中删除@@ [Sam Thomas:10181],该ID将是唯一的,即10181 ..任何使用上述ID标识此整个模式的正则表达式。

echo 'USER TAG NAME WITH PROFILE LINK<br/><hr>';
$text = "hi how are you guys???... @@[Sam Thomas:10181] @@[Jack Daniel:11074] @@[Paul Walker:11043] ";
echo 'REGULAR EXPRESSION USED: <b>/@@\[([^:]*):(\d*)\]/</b>';
echo '<br/>Sample Text<br/>';
echo $text.'<br/>';
$pattern = "/@@\[([^:]*):(\d*)\]/";
$matches = array();
preg_match_all($pattern, $text, $matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
echo '<hr>';
$output = preg_replace($pattern, "<a href=\"http://localhost/$2\" class=\"tooltip\">$1</a>", $text);
echo 'FINAL OUTPUT<br/><hr>';
echo $output;
echo '<br/>==================================================================================<br/>';

\\d* matches any number - if you want to restrict the match to a certain number, replace it with that number: \\d*与任何数字匹配-如果要将匹配限制为某个数字,请用该数字替换:

$pattern = "/@@\[([^:]*):(10181)\]/";

If you expect a variation of numbers, you can use alternation : 如果您希望数字有所变化,则可以使用交替

$pattern = "/@@\[([^:]*):(10181|11074)\]/";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM