Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extracts any one URL in the given string and assigns it to a variable.
<?php
$new_entry['url'] = FALSE;
$new_entry['description'] = 'Hello there! example.com';
$pattern_url = "`("
. "(https?://)?"
. "([a-z\d-]+\.)+"
. "(MUSEUM|TRAVEL|AERO|ARPA|ASIA|EDU|GOV|MIL|MOBI|COOP|INFO|NAME|BIZ|CAT|COM|INT|JOBS|NET|ORG|PRO|TEL|A[CDEFGILMNOQRSTUWXZ]|B[ABDEFGHIJLMNORSTVWYZ]|C[ACDFGHIKLMNORUVXYZ]|D[EJKMOZ]|E[CEGHRSTU]|F[IJKMOR]|G[ABDEFGHILMNPQRSTUWY]|H[KMNRTU]|I[DELMNOQRST]|J[EMOP]|K[EGHIMNPRWYZ]|L[ABCIKRSTUVY]|M[ACDEFGHKLMNOPQRSTUVWXYZ]|N[ACEFGILOPRUZ]|OM|P[AEFGHKLMNRSTWY]|QA|R[EOSUW]|S[ABCDEGHIJKLMNORTUVYZ]|T[CDFGHJKLMNOPRTVWZ]|U[AGKMSYZ]|V[ACEGINU]|W[FS]|Y[ETU]|Z[AMW])+"
. "(:\d+)?"
. "((/([a-z0-9\._/~%\-\+&\#\?!=\(\)@]+)?)*)"
. ")`i";
if ( preg_match( $pattern_url, $new_entry['description'], $match ) ) {
$url = $match[0];
if ( FALSE === strpos($url, '://') ) {
$url = 'http://' . $url;
}
$new_entry['url'] = htmlspecialchars( $url );
$new_entry['description'] = str_replace( $match[0], '', $new_entry['description'] );
}
echo $new_entry['description'];
echo $new_entry['url'] ? ' url: '.$new_entry['url'] : '';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.