pregreplacecallback php,PHP: preg_replace_callback - Manual

Created this to fetch the link and name of an anchor tag. I use this when cleaning an HTML email to text. Using regex for HTML is not recommended but for this purpose I see no issue with it. This is not designed to work for nested anchors.

A note to keep in mind:

I was primarily concerned with valid HTML so if attributes do no use ' or " to contain the values then this will need to be tweaked.

If you can edit this to work better, please let me know.

* Replaces anchor tags with text

* - Will search string and replace all anchor tags with text (case insensitive)

*

* How it works:

* - Searches string for an anchor tag, checks to make sure it matches the criteria

*         Anchor search criteria:

*             - 1 -

*             - 2 - Can have any number of spaces or other attributes before and after the href attribute

*             - 3 - Must close the anchor tag

*

* - Once the check has passed it will then replace the anchor tag with the string replacement

* - The string replacement can be customized

*

* Know issue:

* - This will not work for anchors that do not use a ' or " to contain the attributes.

*         (i.e.- will not be replaced)

*/functionreplaceAnchorsWithText($data) {/**

* Had to modify $regex so it could post to the site... so I broke it into 6 parts.

*/$regex='/(

}

returnpreg_replace_callback($regex,'replaceAnchorsWithText',$data);

}$input='Test 1: .
';$input.='Test 2: .
';$input.='Test 3:
';$input.='This last line had nothing to do with any of this';

echoreplaceAnchorsWithText($input).'

';?>Will output:

Test 1: PHP.NET1(http: //php.net1).

Test 2: PHP.NET2(HTTP: //PHP.NET2).

Test 3: php.net3 (is still an anchor)

This last line had nothing to do with any of this

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值