0

I need to verify a text to show it in the page of a website. I need to transform all urls links of the the same website(not others urls of other websites) in links. I need to involve all them with the tag <a>. The problem is is the property href, that I need to put the correct url inside it. I am trying to verify all the the text and if I find a url, I need to verify if it contains the substring "http://". If not, I must put it in the href property. I did some attempt, but all their aren't working yet :( . Any idea how can I do this?

My function is below:

$string = "This is a url from my website: http://www.mysite.com.br and I have a article interesting there, the link is  http://www.mysite.com.br/articles/what-is-psychology/205967. I need that the secure url link works too https://www.mysite.com.br/articles/what-is-psychology/205967. the following urls must be valid too: www.mysite.com.br and mysite.com.br";

function urlMySite($string){
    $verifyUrl = '';
    $urls = array("mysite.com.br");

    $text = explode(" ", $string);

    $alltext = "";

    for($i = 0; $i < count($texto); $i++){
        foreach ($urls as $value){
            $pos = strpos($text[$i], $value);

            if (!($pos === false)){
                $verifyUrl = " <a href='".$text[$i]."' target='_blank'>".$text[$i]."</a>  ";   

                if (strpos($verifyUrl, 'http://') !== true) {                   
                    $verifyUrl = " <a href='http://".$text[$i]."' target='_blank'>".$text[$i]."</a>  ";
                } 

                $alltext .= $verifyUrl;
            } else {
                $alltext .= " ".$text[$i]." ";
            }
        }       
    }
    return $alltext;
}
DiChrist
  • 351
  • 7
  • 18

1 Answers1

0

You should use PREG_MATCH_ALL to find all occurances of the URL and replace each of the Matches with a clickable Link.

You could use this function:

function augmentText($text){
    $pattern = "~(https?|file|ftp)://[a-z0-9./&?:=%-_]*~i";
    preg_match_all($pattern, $text, $matches);
    if( count($matches[0]) > 0 ){
        foreach($matches[0] as $match){
            $text = str_replace($match, "<a href='" . $match . "' target='_blank'>" . $match . "</a>", $text);
        }
    }
    return $text;
}

Change the reguylar expression pattern to match only the URL's you want to make clickable.

Good luck

Cagy79
  • 1,610
  • 1
  • 19
  • 25
  • Hello Cagy79, preg_match_all looks like better. But the two last occurences havent't be caught. How Can I can put the protocol optional in this case? – DiChrist Nov 03 '16 at 14:49
  • You could use https://regex101.com/ to play with the patterns to see if it matches your needs. You could check other Questions on SO for the pattern you need. Example: http://stackoverflow.com/questions/1141848/regex-to-match-url – Cagy79 Nov 03 '16 at 14:50
  • If you like the answer, then please accept it. Thanks. – Cagy79 Nov 04 '16 at 11:27