doupu7651 2013-08-11 15:20
浏览 81

如何使用preg_replace从PHP字符串中删除链接

I'm using a chat bot script, if a user name was test@test.com the bot will reply @ <a href= mailto:test@test.com>test@test.com</a> with a mailto link. I want the reply to be only test@test.com without the link, I tried preg_replace and str_replace but I don't really know the exact code to use, I've tried the following but didnt work !

$name = preg_replace('/<a href="([^<]*)">([^<]*)<\/a>/', '', $name);

The whole code I'm using for replacements is this:

$name = str_replace (chr(0xc2).chr(0xa0), "_", $name);
$name = str_replace ("'", "", $name);
$name = str_replace ("&quot;", '"', $name);
$name = str_replace ("&amp;", "&", $name);
$name = str_replace ("&lt;", "", $name);
$name = str_replace ("&gt;", "", $name);
$name = str_replace ("&", "_", $name);
$name = str_replace ("*", "_", $name);
$name = preg_replace('/[^ \p{L}\p{N} \@ \_ \- \.\#\$\&\!]/u', '', $name);
$name = preg_replace('/<a href="([^<]*)">([^<]*)<\/a>/', '', $name);
  • 写回答

2条回答 默认 最新

  • doubi3996 2013-08-11 15:37
    关注

    Why do you want to replace it? Just use preg_match() with a regex similar to this:

    <a href=[^>]+>([^<]*)</a>

    so overall your code would look like this

    <?php
    $regex = '#<a href=[^>]+>([^<]*)</a>#';
    $email = '<a href= mailto:test@test.com>test@test.com</a>';
    
    preg_match($regex, $email, $matches);
    var_dump($matches[1]);
    /*
    output:
    string(13) "test@test.com"
    */
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100