dtntjwkl83750 2014-12-14 13:28
浏览 40
已采纳

使用php在函数中使用多个正则表达式

I wanted to pass data that contains url within it, and the url will be converted to click-able links, but the issue is that when i run the function, it reiterate 3 times and the data is treated 3 times. How can I have a single data output? I tried removing the concatenation .= to just = but then, only the last pattern is being treated. I want it in 3 pattern because I want to add http to the href when a user input is www.ivotism.com, it will be <a href="http//www.ivotism.com">www.ivotism.com</a> instead of <a href="www.ivotism.com">www.ivotism.com</a>.

function linkify($inputText) {
        //URLs starting with http://, https://, or ftp://
        $replacePattern1 = '/(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i';
        $replacedText .=  preg_replace($replacePattern1, '<a href="$1" target="_blank">$1</a>', $inputText);

        //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
        $replacePattern2 = '/(^|[^\/])(www\.[\S]+(\b|$))/i';
        $replacedText .=  preg_replace($replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>', $inputText);

        //Change email addresses to mailto:: links.
        $replacePattern3 = '/(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/i';
        $replacedText .=  preg_replace($replacePattern3, '<a href="mailto:$1">$1</a>', $inputText);

        return $replacedText;
    }

I run the code as shown below:

$ab = "<br>1 http://www.ivotism.com <br>2 https://www.ivotism.com/hom.php?u=kira&id=2 <br>3 ftp://www.ivotism.com <br>4 w www.ivotism.com <br>5 info@ivotism.com"; echo 
linkify($ab);

This is the result I got:

  1. 1 http://www.ivotism.com
  2. 2 https://www.ivotism.com/hom.php?u=kira&id=2
  3. 3 ftp://www.ivotism.com
  4. 4 www.ivotism.com
  5. 5 info@ivotism.com
  6. 1 http://www.ivotism.com
  7. 2 https://www.ivotism.com/hom.php?u=kira&id=2
  8. 3 ftp://www.ivotism.com
  9. 4 www.ivotism.com
  10. 5 info@ivotism.com
  11. 1 http://www.ivotism.com
  12. 2 https://www.ivotism.com/hom.php?u=kira&id=2
  13. 3 ftp://www.ivotism.com
  14. 4 www.ivotism.com
  15. 5 info@ivotism.com
  • 写回答

1条回答 默认 最新

  • douwo3665 2014-12-14 13:46
    关注

    You can perform all the replacements in a single call to preg_replace, by putting the regular expressions and replacements into arrays.

    $resultText = preg_replace(array($replacePattern1, $replacePattern2, $replacePattern3),
                               array($replaceSub1, $replaceSub2, $replaceSub3),
                               $inputText);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效