我在Java webapp中有一个所见即所得的文本区域.用户可以输入文本并对其进行样式设置或粘贴一些已经HTML格式的文本.
我想要做的是链接文本.这意味着,将文本中所有可能的URL转换为"工作对应",即添加<a href ="..."> ... </ a>.
当我只有纯文本时,此解决方案有效:
String r = "http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
Pattern pattern = Pattern.compile(r, Pattern.DOTALL | Pattern.UNIX_LINES | Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(comment);
comment = matcher.replaceAll("<a href=\"$0\">$0</a>"); // group 0 is the whole expression
Run Code Online (Sandbox Code Playgroud)
但问题是当有一些已经格式化的文本时,即它已经有<a href ="..."> ... </ a>标签.
因此,当我在两个HTML标记(<a>)之间找到文本时,我正在寻找一种不匹配的模式.我已阅读本可以实现前瞻或回顾后,但我仍然不能使它发挥作用.我确信我做错了因为正则表达式仍然匹配.是的,我一直在玩/调试组,将$ 0改为$ 1等.
有任何想法吗?
我想在链接尚未在链接中的字符串中查找 URL
我当前的代码:
$text = "http://www.google.com is a great website. Visit <a href='http://www.google.com' >http://google.com</a>"
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if(preg_match($reg_exUrl, $text, $url)) {
$links = preg_replace($reg_exUrl, '<a href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $_page['content']['external_links']);
}
Run Code Online (Sandbox Code Playgroud)
问题在于它返回了两次链接(这就是它返回的内容):
<a href="http://www.google.com" rel="nofollow">http://www.google.com</a> is a great website. Visit <a href='<a href="http://www.google.com" rel="nofollow">http://www.google.com</a>' ><a href="http://www.google.com" rel="nofollow">http://www.google.com</a></a>
Run Code Online (Sandbox Code Playgroud) 我想写一个正则表达式,它将用链接替换单词Paris,因为只有单词没有准备好作为链接的一部分.
例:
i'm living <a href="Paris" atl="Paris link">in Paris</a>, near Paris <a href="gare">Gare du Nord</a>, i love Paris.
Run Code Online (Sandbox Code Playgroud)
会成为
i'm living.........near <a href="">Paris</a>..........i love <a href="">Paris</a>.
Run Code Online (Sandbox Code Playgroud) 我想找到文本中的所有链接,如下所示:
Test text http://hello.world Test text
http://google.com/file.jpg Test text https://hell.o.wor.ld/test?qwe=qwe Test text
test text http://test.test/test
Run Code Online (Sandbox Code Playgroud)
我知道我需要使用preg_match_all,但只有头脑中的想法:从http | https | ftp开始搜索并在文本的空格或末尾出现的结束搜索,这就是我真正需要的所有内容,因此所有链接都可以正确找到.
任何人都可以帮助我使用php regexp模式?
我想我需要在模式结束时使用断言,但现在无法理解它们的正确用法.
有任何想法吗?感谢名单!