Quick actions

cmd+k|ctrl+k

Navigation

Languages

PHP turn URL or Email into link if not exist alrea

Snippet info

Language

Php

Visibility

public

Author

myles

Created

2022-02-01T23:39:55.582657Z

Updated

2022-02-02T00:28:05.303047Z

<?php

$link_html = 'This link already exits: <a href="http://googele.com" target="_blank">link</a> but not this: http://google.com link or https://google.com. Email already in a link <a href="mailto:[email protected]">[email protected]</a> and one not: [email protected].';

// The beauty of this is it will also not include ending punctuation (!,.) and works with [email protected]

function replace_links( $content ){
	$content = preg_replace('"<a[^>]+>.+?</a>(*SKIP)(*FAIL)|(https?:\/\/\S+?)(?=[.,!?]?(\s|$))"', '<a href="$0">$0</a>', $content);
	$content = preg_replace('"<a[^>]+>.+?</a>(*SKIP)(*FAIL)|(\S+@\S+\.\S+?)(?=[.,!?]?(\s|$))"', '<a href="mailto:$0">$0</a>', $content);
	return $content;
}

echo replace_links( $link_html );
INFO