using php preg_replace to change html link's href attribute

后端 未结 3 2130
天涯浪人
天涯浪人 2021-01-05 10:31

I\'m trying to replace all link href\'s in a large string with a different URL. With the following code It seems to replace only the 2nd link leaving the first one intact, c

相关标签:
3条回答
  • 2021-01-05 10:35

    Just use the greedy operator in your regex like this:

    '/<a(.*?)href="(.*?)"(.*?)>/'
    
    0 讨论(0)
  • 2021-01-05 10:38

    Slight modifications to Aurelio De Rosa's answer:

    '/<a(.*?)href=(["\'])(.*?)\\2(.*?)>/i'
    
    0 讨论(0)
  • 2021-01-05 10:42

    Instead of any char . use any not (^) quote [^"]

    echo preg_replace('/<a(.*)href="([^"]*)"(.*)>/','<a$1href="javascript:alert(\'Test\');"$3>',$string_of_text);
    
    0 讨论(0)
提交回复
热议问题