简体   繁体   中英

Find URL in string, replace it and alter href

I've currently got a few DB entries which look like this:

1. This is some text http://www.sitehere.com more text
2. Text https://www.anothersite.com text text text
3. http://sitehere.com http://sitehereagain.com
4. Just text here blabla

I am trying to filter those entries while printing them and add infront of all the urls http://anothersite.com/? . Also put the new url destination as link but keep the original url as text:

text text <a href="http://anothersite.com/?http://sitehere.com">http://sitehere.com</a> text

Until now I've managed to add the http://anothersite.com/? part with the following code:

$result = preg_replace('/\bhttp:\/\/\b/i', 'http://anothersite.com/?http://', $input);
$result = preg_replace('/\bhttps:\/\/\b/i', 'http://anothersite.com/?https://', $input);

But the ahref is not the way I want it. Instead it is:

text text <a href="http://anothersite.com/?http://sitehere.com">http://anothersite.com/?http://sitehere.com</a> text

PS: I am not looking for a javascript solution :) Thank you!

This following code should work. There are a few large changes I made. The first one is I am using preg_replace_callback instead of preg_replace so I am able to properly encode the URL and have more control over the output. The other change is I'm matching the whole domain so the callback function can insert the URL between the <a> tags and also can add it to the hyperlink.

<?php

    $strings = array(
        'This is some text http://www.sitehere.com more text',
        'Text https://www.anothersite.com text text text',
        'http://sitehere.com http://sitehereagain.com',
        'Just text here blabla'
    );

    foreach($strings as $string) {
        echo preg_replace_callback("/\b(http(s)?:\/\/[^\s]+)\b/i","updateURL",$string);
        echo "\n\n";
    }

    function updateURL($matches) {
        $url = "http://anothersite.com/?url=";
        return '<a href="'.$url.urlencode($matches[1]).'">'.$matches[1].'</a>';
    }

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM