php在正则表达式的字符串中查找#

时间:2015-09-29 18:25:21

标签: php regex regex-negation

我有一个php变量,我需要将#value值显示为链接模式。 代码看起来像这样。

$reg_exUrl = "/\#::(.*?)/";

 // The Text you want to filter for urls
$text = "This is a #simple text from which we have to perform #regex    operation";

// Check if there is a url in the text
   if(preg_match($reg_exUrl, $text, $url)) {

   // make the urls hyper links
    echo preg_replace($reg_exUrl, '<a href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text);

   } else {

   // if no urls in the text just return the text
     echo "IN Else #$".$text;

 }

3 个答案:

答案 0 :(得分:2)

通过使用\ w,您可以匹配包含字母数字字符和下划线的单词。用这个改变你的表达:

$reg_exUrl = "/#(.*?)\w+/"

答案 1 :(得分:1)

我不清楚你到底需要匹配什么。如果您想要替换#后跟任何单词chars:

$text = "This is a #simple text from which we have to perform #regex    operation";

$reg_exUrl = "/#(\w+)/";
echo preg_replace($reg_exUrl, '<a href="$0" rel="nofollow">$1</a>', $text);

//Output:
//This is a <a href="#simple" rel="nofollow">simple</a> text from which we have to perform <a href="#regex" rel="nofollow">regex</a>    operation

替换使用$0来引用匹配的文本和$1第一组。

答案 2 :(得分:1)

$reg_exUrl = "/\#::(.*?)/";

由于以下原因,这不匹配

1。无需转义#,这是因为它不是特殊字符。

2。,因为您只想匹配#后跟一些字词,所以不需要::

3。 (.*?)因量词?而尝试匹配最少的单词。所以它与你需要的单词长度不符。

如果您仍想按照模式进行操作,可以将其修改为

$reg_exUrl = "/#(.*?)\w+/"请参阅demo

但是效率更高的是

$reg_exUrl = "/#\w+/"。见demo