doutou1922 2015-10-28 20:30
浏览 55
已采纳

PHP正则表达式preg_replace函数Joomla! 插入

I want to create plugin that finds and replaces phone numbers with a linked number for mobile. This is a php function that I have written for Joomla to use to replace a phone number...

protected function clickToCall(&$text, &$params){
    // phone number pattern...
    $pattern = '~(\+0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}~';
    //replacement pattern...
    $replacement = '<a href="tel:$1$2">$1$2</a>';
    //use preg_replace to actually replace the pattern
    $text = preg_replace($pattern, $replacement, $text);
    //return the new value
    return true;
}

Right now the function finds the pattern and just replaces it with an empty link. How can insert the phone number found by regex into a link?

  • 写回答

1条回答 默认 最新

  • donglunzai4288 2015-10-28 20:49
    关注

    The problem is that you are using $1 and $2 backreferences that refer to Group 1 (i.e. substring captured with (\+0?1\s)?) and non-existent Group 2 (thus, it is an empty string) rather than to the whole match (that can be referred to with the help of $0 or \0).

    Here is a fix:

    $text = 'Phone +1 (234) 345 6543 to obtain a free copy.';
    $pattern = '~(\+0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}~';
    $replacement = '<a href="tel:$0">$0</a>';
    echo $text = preg_replace($pattern, $replacement, $text);
    

    See IDEONE demo

    See more about Back references in PHP Manual.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀