简体   繁体   English

PHP使用正则表达式在字符串中查找#

[英]php find # in string with regex

I have a php variable where I need to show #value Values as link pattern. 我有一个php变量,我需要在其中显示#value值作为链接模式。 The code looks like this. 代码看起来像这样。

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

 }

By using \\w, you can match a word contains alphanumeric characters and underscore. 通过使用\\ w,您可以匹配包含字母数字字符和下划线的单词。 Change your expression with this: 以此更改您的表情:

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

It's not clear to me exactly what you need match. 我不清楚您需要匹配什么。 If you want to replace a # followed by any word chars: 如果要替换#后跟任何字符char:

$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

The replacement uses $0 to refer to the text matched and $1 the first group. 替换使用$0表示匹配的文本, $1表示第一组。

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

This doesn't match because of the following reasons 由于以下原因,此不匹配

1. there is no need to escape # , this is because it is not a special character. 1.不需要转义# ,这是因为它不是特殊字符。

2. since you want to match just # followed by some words, there is no need for :: 2.由于您只想匹配#后跟一些单词,因此不需要::

3. (.*?) tries to match the least possible word because of the quantifier ? 3. (.*?)试图匹配最小的单词,因为使用了量词? . So it won't match the required length of word you need. 因此,它与您所需的单词长度不匹配。

If you still want to go by your pattern, you can modify it to 如果您仍然想按照自己的样式进行操作,则可以将其修改为

$reg_exUrl = "/#(.*?)\\w+/" See demo $reg_exUrl = "/#(.*?)\\w+/"参见演示

But a more efficient one that still works is 但是,仍然有效的更有效的方法是

$reg_exUrl = "/#\\w+/" . $reg_exUrl = "/#\\w+/" see demo 观看演示

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

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