dsdtszi0520538 2012-09-13 07:51 采纳率: 100%
浏览 17
已采纳

正则表达式匹配单,双没有报价

I use preg_replace function that has to clear all the rel and target attributes from the $body and to replace them with other values. Here it is:

    $patterns = array();
    $patterns[] = '/<a(.*) rel="([^"]*)"(.*)>/';
    $patterns[] = '/<a(.*) target="([^"]*)"(.*)>/';
    $patterns[] = '/<a(.*)>/';

    $replacements = array();
    $replacements[] = '<a$1$3>';
    $replacements[] = '<a$1$3>';
    $replacements[] = '<a rel="nofollow" target="_blank"$1>';

    $body = preg_replace($patterns,$replacements,$body);

The problem is that it does not match single and no-quotes. Also if there is any better approach for clearing the rel and target attributes from the links and setting them with others, please advise.

Thanks

EDIT: $body:

    $body = '<a href="TEST">Link1</a>
      <a href="TEST" rel=\'lqlqlq\'>Link2</a>
      <a href="TEST" target="_blank" rel="lqlqlq">Link3</a>
              <a href="TEST" target=_blank rel=lqlqlq>Link4</a>';

And also every other option for working links due to the text is user defined and probably some users are going to cheat. My goal - all of the links in $body to be with defined rel and target attributes no matter what the user has entered.

  • 写回答

3条回答 默认 最新

  • dpf25323 2012-09-13 08:08
    关注

    If you don't want to match anything else at the same time I suggest you don't and preserve system resources.

    $patterns[] = "/rel=[\"\']?([\w]+)[\"\']?/";
    $patterns[] = "/target=[\"\']?([_a-zA-Z]+)[\"\']?/"
    

    I'm not the best at REGEX but as far as I know this will save you some time.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程