Home > Mobile >  Laravel convert strings to clickabe links
Laravel convert strings to clickabe links

Time:12-10

I am trying to convert links, mail addresses and numbers to links from my description column but I only can make 1 of them to work at the time, what I'm looking for is solution to preg_replace multiple conditions.

Here is what I have currently that converts links to clickable a tags:

public function getDescriptionAttribute($string) {
  return preg_replace('@(https?://([-\w\.] [-\w]) (:\d )?(/([\w/_\.#-]*(\?\S )?[^\.\s])?)?)@', '<a href="$1" rel="noopener nofollow" target="_blank">$1</a>', $string);
}

Logic

  1. If description has link convert to clickable (http/https)
  2. If description has mail address convert to clickable (mailto)
  3. If description has numbers convert to clickable (tel)

let say I have following string in my database (description column)

http://google.com

[email protected]

 1818254545400

what I get from that string is following result (based on my code above)

Screenshot

one

Any idea?

CodePudding user response:

You might for example use an approach using a pattern with 3 capture groups, one for each option.

Then use preg_match_callback to check for the group values, and based on that determine the replacement.

(https?://\S )|([^\s@] @[^\s@] )|(\ \d )

You can make the pattern for the groups as specific as you would like of course.

Regex demo | PHP demo

function getDescriptionAttribute($string) {
    $pattern = "~(https?://\S )|([^\s@] @[^\s@] )|(\ \d )~";
    
    return preg_replace_callback($pattern, function($matches) {
        
        $template = '<a href="%1$s%2$s" rel="noopener nofollow" target="_blank">%2$s</a>';
        
        if ($matches[1] !== "") return sprintf($template, "", $matches[1]);        
        if ($matches[2] !== "") return sprintf($template, "mailto:", $matches[2]);        
        if ($matches[3] !== "") return sprintf($template, "tel:", $matches[3]);
    }, $string);    
}

$str = 'http://google.com
[email protected]
 1818254545400';

echo getDescriptionAttribute($str);

Output

<a href="http://google.com" rel="noopener nofollow" target="_blank">http://google.com</a>
<a href="mailto:[email protected]" rel="noopener nofollow" target="_blank">[email protected]</a>
<a href="tel: 1818254545400" rel="noopener nofollow" target="_blank"> 1818254545400</a>
  • Related