php - 使用 regex/php 删除文本中的嵌套链接
问题描述
我有一些带有很多链接的文本,其中一些有嵌套链接。我试图创建一个正则表达式来删除链接锚内的任何链接,留下锚文本。
我的想法是使用正则表达式来查找所有文本锚点,并将它们替换为相同的文本并删除标签。但是,我无法实现它。
例子:
<p>Any text <a href="#">a correct link</a> more text <a href="#">some <a href="#">word</a>.</a><p>
预期结果
<p>Any text <a href="#">a correct link</a> more text <a href="#">some word.</a><p>
我正在尝试的是它遵循的内容:
$pattern="/<a.*>([a-zA-Z ].*)<\/a>/";
preg_match_all ($pattern , $text, $matches);
foreach($matches as $match)
{
$text=str_replace($match[0],strip_tags($match[0],'<b>'),$text);
}
解决方案
您可以使用以下内容:
$pattern = '/<a.*>.*(<a.*>(.*)<\/a>(.*))<\/a>/m';
$text = '<p>Any text <a href="#">a correct link</a> more text <a href="#">some <a href="#">word</a>.</a><p>';
preg_match_all($pattern, $text, $matches, PREG_SET_ORDER, 0);
$matches = $matches[0];
$to_search = $matches[1];
unset($matches[0], $matches[1]);
$to_replace = '';
foreach($matches AS $match)
$to_replace .= $match;
$str = str_replace($to_search, $to_replace, $text);
我希望这有帮助。
如果您需要更多帮助,请告诉我。
推荐阅读
- c# - 为什么创建自定义 AuthorizeAttribute 时 base.IsAuthorized 总是返回 false?
- angular - Angular为Firestore创建搜索栏
- python - 从一系列字符串中删除字符串列表
- c# - 在 PartialView 中仅查看数据库中包含“Foo”的行
- javascript - 如何解决自定义抽屉组件可触摸 onPress 屏幕切换在 React-Native 中不起作用?
- maven - 类路径上的 UIComponent 两次,应该从哪里导入?
- php - 照亮\广播\广播异常没有消息
- c++ - 为什么某些 STL 函数(例如“find”)不需要“std::”(有时)?
- c# - 带有左连接子查询的 SQL 到 LINQ
- python - 尝试使用 jupyter notebook 中下拉菜单中的值绘制图形