Regular Expression to Search+Replace href=“URL”

前端 未结 2 1468
感情败类
感情败类 2021-01-01 02:40

I\'m useless with regular expressions and haven\'t been able to google myself a clear solution to this one.

I want to search+replace some text ($content) for any url

相关标签:
2条回答
  • 2021-01-01 03:04

    Here is the gist of what I came up with. Hopefully it helps someone:

    $content = get_the_content();
    $pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
    $newurl = get_permalink();
    $content = preg_replace($pattern,$newurl,$content);
    
    echo $content;
    

    Mucho thanko to @WiseGuyEh

    0 讨论(0)
  • 2021-01-01 03:22

    This should do the trick- you can test it here

    (?<=href=("|'))[^"']+(?=("|'))
    

    It uses lookahead and lookbehind to assert that anything it matches starts with href=" or href=' and makes sure that it ends with a single or double quote.

    Note: the regex will not be able to determine if this is a valid html document- if there is a mix of single then double quotes used to enclose a href value, it will ignore this error!

    0 讨论(0)
提交回复
热议问题