preg_replace一个没有结束的#标签;

时间:2016-12-07 05:40:22

标签: php regex

我目前正在使用preg_replace来替换html链接中提到的主题标签,如下所示。问题是有可能会有html代码以及被检查。因此,color: #000000;之类的某些CSS会强制它尝试将该十六进制代码转换为链接。

如果一个单词的最后一个字母是;,我基本上需要我的正则表达式来忽略任何preg_replace。这就是我目前所拥有的:

$str = preg_replace('/#([a-zA-Z0-9!_%]+)/', '<a href="http://example.com/tags/$1">#$1</a>', $str);

示例输入:'I like #action movies!'
预期输出:I like <a href="http://example.com/tags/action">#action</a> movies!'

我无法使用字符串的结尾来检查这一点,因为在任何给定时间都会检查文本块,因此提供的字符串可能是#computer text text text #computer

感谢任何帮助。

5 个答案:

答案 0 :(得分:1)

直到一个regEx guru来救你(如果有的话......)并且因为你是PHP的;这是一个几行代码的解决方案。

$str="hi #def; #abc #ghi"; // just a test case (first one need be skipped)

if (preg_match_all('/#([a-zA-Z0-9!_%]+.?)/', $str,$m)){
   foreach($m[1] as $k) if(substr($k,-1)!=';') {
      $k=trim($k);
      $str=str_replace("#$k","<a href='http://wxample.com/tags/$k'>#$k</a>",$str);
    }
}

print "$str\n";

答案 1 :(得分:1)

在正则表达式中,您可以检查标签旁边是否有;非字母数字,行尾或字符串结尾:

/#([a-zA-Z0-9!_%]+)([^;\w]{1}|$)/

然后相应地使用$ 1和$ 2

'<a href="http://example.com/tags/$1">#$1</a>$2'

您的代码看起来像

$str = preg_replace('/#([a-zA-Z0-9!_%]+)([^;\w]{1}|$)/', '<a href="http://example.com/tags/$1">#$1</a>$2',$str);

在这里你可以看到一些测试:https://regex101.com/r/yN4tJ6/65

答案 2 :(得分:0)

你可以添加一个条件来检查最后一个字符串是什么;或不使用它。 示例:

if (substr($str, -1)==';'){
//do nothing 
}
else {
$str = preg_replace('/#([a-zA-Z0-9!_%]+)/', '<a href="http://example.com/tags/$1">#$1</a>', $str);
}

希望得到这个帮助。

答案 3 :(得分:0)

嗯,你可以使用下面的代码,实际上我是正则表达式的新手,所以它不是那么专业,但它有效,这里是

$data = "<p style='color:#00000;'>Heloo</p> #computer text text text #computer #say #goo1d #sd! #say_hello";
echo preg_replace("/(?<!\:)(\s+)\#([\w]+)(?!\;)/",'<a href="http://example.com/tags/$2">#$2</a>',$data);

这个表达式我用过

/(?<!\:)(\s+)\#([\w]+)(?!\;)/

输出

<p style='color:#00000;'>Heloo</p> <a href="http://example.com/tags/computer">#computer</a> text text text <a href="http://example.com/tags/computer">#computer</a> <a href="http://example.com/tags/say">#say</a> <a href="http://example.com/tags/goo1d">#goo1d</a> <a href="http://example.com/tags/sd">#sd</a>! <a href="http://example.com/tags/say_hello">#say_hello</a>

我希望它有所帮助。

答案 4 :(得分:0)

这个正则表达式应该有效:

{  
  "links": [{
    "href": "https://api.paypal.com/v1/payments/sale/36C38912MN9658832",
    "rel": "self",
    "method": "GET"
  }, {
    "href": "https://api.paypal.com/v1/payments/sale/36C38912MN9658832/refund",
    "rel": "refund",
    "method": "POST"
  }, {
    "href": "https://api.paypal.com/v1/payments/payment/PAY-5YK922393D847794YKER7MUI",
    "rel": "parent_payment",
    "method": "GET"
  }]
}

演示:https://regex101.com/r/KrRiD3/2

您的PHP代码:

#([\w!%]+(?=[\s,!?.\n]|$))

输出:

  

我喜欢#strategy场比赛#f1f1f1; #e2e2e2; #action场比赛!

相关问题