0

I have this function to replace a text with an url to url link. The callback is used to check if it has http or not in the link, if it has not, add http on it:

<?php

function toLink($titulo){
    $url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i'; 

    $titulo = preg_replace_callback($url, function($matches) {
        $url = $matches[0];
        if (!preg_match('/^https?:\/\//', $url)) {
            $url = 'http://'.$matches[0];
            $url = '<a href="'.$url.'" target="_blank" 
                       title="'.$url.'">'.$url.'</a>';
        }
    },$titulo);


    return $titulo;
}


echo toLink("hi from www.google.com");

The return value is hi from where is my link?

11
  • 2
    I haven't really looked at the regex, but shouldn't the callback return something? Commented Jan 18, 2019 at 17:01
  • 2
    return $url seems like a good bet to me :-) Commented Jan 18, 2019 at 17:02
  • 1
    At the end of the callback (function($matches) { ... }), after you've created the URL you want, return it Commented Jan 18, 2019 at 17:05
  • 1
    You're welcome! Commented Jan 18, 2019 at 17:14
  • 1
    @sal I really thought this must have been a duplicate, because it seems like such an easy mistake to make, but I haven't been able to find one. Your answer is fine, no need to add another one IMO, but thanks anyway. Commented Jan 18, 2019 at 17:27

2 Answers 2

1

Your callback needs to return the string (or value) that should be inserted. This gives you more information.

Sign up to request clarification or add additional context in comments.

Comments

1

As mentioned in the comments, the callback function must return a value, to make this fully work. To tie things together, you just need a return $url statement in the end of the callback, like this:

function toLink($titulo){
    $url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i'; 

    $titulo = preg_replace_callback($url, function($matches) {
        $url = $matches[0];
        if (!preg_match('/^https?:\/\//', $url)) {
            $url = 'http://'.$matches[0];
            $url = '<a href="'.$url.'" target="_blank" 
                       title="'.$url.'">'.$url.'</a>';
        }
        return $url;    // <---- return the $url
    },$titulo);


    return $titulo;
}


echo toLink("hi from www.google.com");

Check the result on https://eval.in/1079110

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.